package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.config.RedisUtil;
import com.haoze.common.constant.Constant;
import com.haoze.common.enumeration.CirculationModelEnum;
import com.haoze.common.enumeration.CirculationTypeEnum;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.model.OrdersFileIndexDataEntity;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.*;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.HttpClientUtil;
import com.haoze.common.utils.JSONUtils;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.aop.NurseLogAop;
import com.haoze.nurseapp.dao.*;
import com.haoze.nurseapp.dto.*;
import com.haoze.nurseapp.dto.Assessment.CirculationTemplateDTO;
import com.haoze.nurseapp.dto.Assessment.CommonTaskCirculationDTO;
import com.haoze.nurseapp.enumeration.OperationTypeEnum;
import com.haoze.nurseapp.enumeration.VarCodeEnum;
import com.haoze.nurseapp.model.*;
import com.haoze.nurseapp.service.NurseFileIndexService;
import com.haoze.nurseapp.service.PatientCirculationService;
import com.haoze.nurseapp.service.PatientService;
import com.haoze.nurseapp.vo.Element;
import com.haoze.nurseapp.vo.EmrFile;
import com.haoze.nurseapp.vo.EmrFileData;
import com.haoze.nurseapp.vo.patient.InHospitalPatientVO;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.common.utils.CopyOnWriteMap;
import org.jasypt.commons.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Clob;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class PatientCirculationServiceImpl implements PatientCirculationService {

    @Resource
    CommonTaskCirculationMapper commonTaskCirculationMapper;

    @Resource
    CirculationTemplateMapper circulationTemplateMapper;

    @Resource
    NurseFileIndexService fileIndexService;

    @Resource
    PatientService patientService;

    @Resource
    CirculationLogMapper circulationLogMapper;

    @Resource
    PatientInHospitalMapper patientInHospitalMapper;

    @Resource
    NurseTeamDutyMapper nurseTeamDutyMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    NurseTeamMapper nurseTeamMapper;

    @Resource
    MavEmrCoreDictMapper dictMapper;

    @Value("${his.url.circulation}")
    private String circulationUrl;

    @Value("${his.url.circulation2}")
    private String circulationUrl2;
    //private String circulationUrl2 = "http://172.30.1.68:8181/ZHYY/HospitalSelfHelpInterface";

    @Value("${his.url.cost}")
    private String cost;

    @Value("${his.url.environmentFlag}")
    private String environmentFlag;

    @Value("${his.url.cost}")
    private String emrnewUrl;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    SysDeptDictMapper sysDeptDictMapper;

    //@Autowired
    //private MongoTemplate doctorMongoTemplate;

    @Value("${spring.profiles.active}")
    private String activeType;

    @Autowired
    private TaskExecuteMapper taskExecuteMapper;

    @Autowired
    private NurseFileIndexService nurseFileIndexService;

    @Autowired
    OrdersFileIndexMapper ordersFileIndexMapper;

    @Resource
    private EmrCatalogMapper emrCatalogMapper;

    private final static String PARAM = "%\"listWarn\":\"1\"%";

    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);

    @Override
    public Result queryTampList(String modelName, String inpatNum, String circulationLogId) {
        List<CirculationTemplateDTO> list = circulationTemplateMapper.queryTampList(modelName, inpatNum, circulationLogId);
        //int count=0;
        if (CollectionUtils.isNotEmpty(list)) {
            for (CirculationTemplateDTO circulationTemplateDTO : list) {
                String circulationType = circulationTemplateDTO.getCirculationType();
                String childModelName = circulationTemplateDTO.getModelName();
                if (StringUtils.isNotEmpty(circulationType) && "parent".equals(circulationType)) {
                    if (StringUtils.isNotEmpty(circulationTemplateDTO.getCommonTaskCirculationId())) {
                        circulationTemplateDTO.setTickFlag("1");
                    } else if (StringUtils.isNotEmpty(circulationTemplateDTO.getModelName()) && "admission_ssessment".equals(circulationTemplateDTO.getModelName())) {
                        List<CirculationTemplateDTO> childList = circulationTemplateMapper.queryChildTampList(childModelName, inpatNum, circulationLogId);
                        if (CollectionUtils.isNotEmpty(childList)) {
                            circulationTemplateDTO.setTickFlag("1");
                        }
                    }
                } else {
                    if (StringUtils.isNotEmpty(circulationTemplateDTO.getEmrFileId())) {
                        circulationTemplateDTO.setTickFlag("1");
                    }
                }
                /*if ("system_assessment".equals(circulationTemplateDTO.getParentModel()) ||
                        "discharge_assessment".equals(circulationTemplateDTO.getParentModel()) ||
                        "in_dept_admission_assessment".equals(circulationTemplateDTO.getParentModel()) ||
                        "out_dept_admission_assessment".equals(circulationTemplateDTO.getParentModel())) {
                    if(StringUtils.isNotBlank(circulationTemplateDTO.getEmrFileId())){
                        count++;
                    }
                }*/
            }
            //判断count是否为0
            if ("system_assessment".equals(modelName) ||
                    "discharge_assessment".equals(modelName) ||
                    "in_dept_admission_assessment".equals(modelName) ||
                    "out_dept_admission_assessment".equals(modelName) ||
                    "before_operation_assessment".equals(modelName) ||
                    "afert_operation_assessment".equals(modelName)) {
                //if(count==0 && CollectionUtils.isNotEmpty(list)){
                if (CollectionUtils.isNotEmpty(list)) {
                    //查找最近的每日评估数据
                    Map<String, String> map = circulationTemplateMapper.queryRecentDailyAssessmentByInpatNum(inpatNum);
                    if (map != null) {
                        List<CirculationTemplateDTO> recentDailyAssessmentList = circulationTemplateMapper.queryTampList(map.get("modelName"), inpatNum, map.get("circulationLogId"));
                        if (CollectionUtils.isNotEmpty(recentDailyAssessmentList)) {
                            for (CirculationTemplateDTO circulationTemplateInfo : list) {
                                for (CirculationTemplateDTO circulationTemplateDTO : recentDailyAssessmentList) {
                                    if (circulationTemplateDTO.getTplId().equals(circulationTemplateInfo.getTplId())) {
                                        circulationTemplateInfo.setDailyAssessmentMarker("dailyAssessmentMark");
                                        if (StringUtils.isBlank(circulationTemplateInfo.getEmrFileId()) && StringUtils.isBlank(circulationTemplateInfo.getCommonTaskCirculationId())) {
                                            circulationTemplateInfo.setExceptionFlag(circulationTemplateDTO.getEmrFileId());
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return ResultGenerator.genOkResult(list);
    }

    public Result queryOperationTampList(String modelName, String inpatNum, String circulationLogId) {
        //根据circulationLogId查询流转记录
        CirculationLogEntity circulationLogEntity = circulationLogMapper.queryCirculationLogById(circulationLogId);
        if (circulationLogEntity != null) {
            //if("finish_in_resuscitation".equals(circulationLogEntity.getCirculationModelType())){
            if (CirculationModelEnum.FINISH_IN_RESUSCITATION.getCode().equals(circulationLogEntity.getCirculationModelType())) {
                //找到上一次的的
                CirculationLogEntity previous = circulationLogMapper.queryCirculationLogByParams(circulationLogEntity.getInpatNum(), circulationLogEntity.getCirculationOperateType(), circulationLogEntity.getInpatorderdataId(), circulationLogEntity.getSerialNo() - 2);
                if (previous != null) {
                    List<CirculationTemplateDTO> list = circulationTemplateMapper.queryOperationTampList("transfer_handover", inpatNum, previous.getCirculationLogId());
                    if (list != null && list.size() > 0) {
                        return ResultGenerator.genOkResult(list);
                    }
                }
                //}else if("finish_out_resuscitation".equals(circulationLogEntity.getCirculationModelType()) || "finish_out_operation".equals(circulationLogEntity.getCirculationModelType())) {
            } else if (CirculationModelEnum.FINISH_OUT_RESUSCITATION.getCode().equals(circulationLogEntity.getCirculationModelType()) || CirculationModelEnum.FINISH_OUT_OPERATION.getCode().equals(circulationLogEntity.getCirculationModelType())) {
                //找到上一次的的
                List<CirculationTemplateDTO> list = circulationTemplateMapper.queryOperationTampList("transfer_handover", inpatNum, circulationLogEntity.getCirculationLogId());
                if (list != null && list.size() > 0) {
                    return ResultGenerator.genOkResult(list);
                }
            } else {
                //找到上一次的的
                CirculationLogEntity previous = circulationLogMapper.queryCirculationLogByParams(circulationLogEntity.getInpatNum(), circulationLogEntity.getCirculationOperateType(), circulationLogEntity.getInpatorderdataId(), circulationLogEntity.getSerialNo() - 1);
                if (previous != null) {
                    List<CirculationTemplateDTO> list = circulationTemplateMapper.queryOperationTampList("transfer_handover", inpatNum, previous.getCirculationLogId());
                    if (list != null && list.size() > 0) {
                        return ResultGenerator.genOkResult(list);
                    }
                }
            }
        }
        return ResultGenerator.genOkResult(circulationTemplateMapper.queryTampList(modelName, inpatNum, circulationLogId));
    }

    public Result queryTransferTampList(String inpatNum, String circulationLogId) {
        //根据circulationLogId查询流转记录
        CirculationLogEntity circulationLogEntity = circulationLogMapper.queryCirculationLogById(circulationLogId);
        if (circulationLogEntity != null) {
            if (CirculationModelEnum.WAIT_IN_DEPT.getCode().equals(circulationLogEntity.getCirculationModelType())) {
                //根据医嘱、住院号、查询转科转出完成信息
                CirculationLogEntity previous = circulationLogMapper.queryCirculationLogTransferOut(circulationLogEntity.getInpatNum(), circulationLogEntity.getInpatorderdataId());
                if (previous != null) {
                    List<CirculationTemplateDTO> list = circulationTemplateMapper.queryOperationTampList("physical_sign_record", inpatNum, previous.getCirculationLogId());
                    if (list != null && list.size() > 0) {
                        return ResultGenerator.genOkResult(list);
                    }
                }
            }
        }
        return ResultGenerator.genOkResult(null);
    }


    @Override
    @Transactional
    public Result saveAssessmentFileData(CommonTaskCirculationDTO commonTaskCirculationDTO) {
        String emrFileId = "";
        if (null != commonTaskCirculationDTO && null != commonTaskCirculationDTO.getEmrFile() && null != commonTaskCirculationDTO.getEmrFile().getEmrFileIndexEntity()) {
            emrFileId = fileIndexService.saveFileIndex(commonTaskCirculationDTO.getEmrFile());
        }
        log.info("保存文书后返回emrFileId：：：：：{}", emrFileId);
        saveOperator(commonTaskCirculationDTO.getInpatNum(), commonTaskCirculationDTO.getCirculationTemplateId(), emrFileId, commonTaskCirculationDTO.getCirculationlLogId());
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result queryBedByWardDeptId(String wardDeptId) {
        List<Map<String,String>> list = commonTaskCirculationMapper.queryBedByWardDeptId2(wardDeptId,null,null);
        return ResultGenerator.genOkResult(list);
    }

    public Result queryBedByWardDeptId2(String wardDeptId,String id,Integer page,Integer pageSize,String keyWords,String operationFlag){
        PageHelper.startPage(page, pageSize);
        if(CirculationModelEnum.WAIT_OUT_HOSP.getCode().equals(operationFlag)) {
            //出院
            PageHelper.startPage(page, pageSize);
            List<Map<String, String>> list = circulationLogMapper.queryWaitOutHospitalList(wardDeptId, null,id,operationFlag,keyWords);
            List<Map<String, String>> resultList = new CopyOnWriteArrayList<>();
            if(CollectionUtils.isNotEmpty(list)){
                list.parallelStream().forEachOrdered(x->{
                    Map<String, String> map = new CopyOnWriteMap<>();
                    map.put("id",x.get("bedNo"));
                    map.put("name",x.get("bedNo"));
                    map.put("circulationLogId",x.get("circulationLogId"));
                    map.put("inpatNum",x.get("inpatNum"));
                    map.put("operationFlag",CirculationModelEnum.WAIT_OUT_HOSP.getCode());
                    resultList.add(map);
                });
            }
            PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(resultList);
            return ResultGenerator.genOkResult(pageInfo);
        }else if(CirculationModelEnum.WAIT_OUT_DEPT.getCode().equals(operationFlag)){
            //转科转出
            List<Map<String, String>> list = circulationLogMapper.queryWaitOutHospitalList(wardDeptId, null,id,operationFlag,keyWords);
            List<Map<String, String>> resultList = new CopyOnWriteArrayList<>();
            List<Map<String, String>> lastList = new CopyOnWriteArrayList<>();
            List<String> inpatNumList = new CopyOnWriteArrayList<>();
            if(CollectionUtils.isNotEmpty(list)){
                list.stream().forEach(x->{
                    Map<String, String> map = new CopyOnWriteMap<>();
                    map.put("id",x.get("bedNo"));
                    map.put("name",x.get("bedNo"));
                    map.put("circulationLogId",x.get("circulationLogId"));
                    map.put("inpatNum",x.get("inpatNum"));
                    map.put("operationFlag",operationFlag);
                    inpatNumList.add(x.get("inpatNum"));
                    resultList.add(map);
                });
            }
            String babyFlag = null;
            List<Map<String, String>> pbstetricWardList = circulationLogMapper.queryObstetricWard(wardDeptId,VarCodeEnum.OBSTETRICS_WARD.getVarCode());
            if(CollectionUtils.isNotEmpty(pbstetricWardList)){
                babyFlag="1";
            }
            List<Map<String, String>> notCirculationList = circulationLogMapper.queryBedNoByWardDeptId(wardDeptId,id,keyWords,babyFlag,inpatNumList,null);
            if(CollectionUtils.isNotEmpty(notCirculationList)){
                notCirculationList.stream().forEach(x->{
                    x.put("circulationLogId","");
                    x.put("operationFlag",operationFlag);
                    resultList.add(x);
                });
            }
            int totalLength = 0;
            //排序
            if (CollectionUtils.isNotEmpty(resultList)) {
                if (!org.springframework.util.CollectionUtils.isEmpty(resultList)) {
                    lastList = resultList.stream().sorted(Comparator.comparingInt(PatientCirculationServiceImpl::comparingByBedNo))
                            .collect(Collectors.toList());
                }
                totalLength = lastList.size();

                if (page != 0 && pageSize != 0) {
                    lastList = lastList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
                }
            }
            PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(lastList);
            pageInfo.setTotal(totalLength);
            return ResultGenerator.genOkResult(pageInfo);

        }else{
            List<Map<String,String>> list = commonTaskCirculationMapper.queryBedByWardDeptId2(wardDeptId,id,keyWords);
            PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
            return ResultGenerator.genOkResult(pageInfo);
        }
    }

    private static Integer comparingByBedNo(Map<String, String> map){
        return Integer.parseInt(map.get("id"));
    }
    private static Integer comparingByBedNo2(Map<String, String> map){
        return Integer.parseInt(String.valueOf(map.get("bedNo")));
    }

    @Override
    public Result queryNurseLeaderByWardDeptId(String wardDeptId, String bedNo) {
        List<Map<String, String>> list = commonTaskCirculationMapper.queryNurseLeaderByWardDeptId(wardDeptId, bedNo);
        return ResultGenerator.genOkResult(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    //public Result savePatientInfo(String inpatNum, String wardDeptId) {
    public Result savePatientInfo(Map<String, String> params) {
        //Map<Object, Object> resMap = redisUtil.hmget(inpatNum + "_inHosp");
        //Query query = new Query();
        //query.addCriteria(Criteria.where("inpatNum").is(inpatNum));
        //PatientInHospInfo patientInHospInfo = doctorMongoTemplate.findOne(query, PatientInHospInfo.class);
       /* if (null == resMap) {
            return ResultGenerator.genFailedResult("页面数据由于长时间未保存而失效");
        }*/
        /*if (null == patientInHospInfo) {
            return ResultGenerator.genFailedResult("页面数据由于长时间未保存而失效");
        }*/
        //验证是否必填资料是否全部完成
        //List<String> isAllFinish = circulationTemplateMapper.checkIsFinish(inpatNum, "admission_ssessment");
        /*   */

        String inpatNum = (String) params.get("inpatNum");
        String bedNo = (String) params.get("bedNo");
        String deptId = (String) params.get("deptId");
        String doctorPersonId = (String) params.get("doctorPersonId");
        String nurseId = (String) params.get("nurseId");
        String wardDeptId = (String) params.get("wardDeptId");
        //待入院
        String circulationLogId = (String) params.get("circulationLogId");
        //已入院
        String newCirculationLogId = (String) params.get("newCirculationLogId");
        String inDatetime = (String) params.get("inDatetime");


        //验证是否必填资料是否全部完成
        //List<String> isAllFinish = circulationTemplateMapper.checkIsFinish(inpatNum, "admission_ssessment");
        List<String> isAllFinish = circulationTemplateMapper.checkIsFinish(inpatNum, "admission_ssessment");
        if (null != isAllFinish && isAllFinish.size() > 0) {
            return ResultGenerator.genFailedResult(StringUtils.join(isAllFinish.toArray()) + "未完成，无法保存");
        }

        isAllFinish = circulationTemplateMapper.checkIsFinish(inpatNum, "in_hosp");
        if (null != isAllFinish && isAllFinish.size() > 0) {
            if (!(isAllFinish.size() == 1 && "入院评估".equals(isAllFinish.get(0)))) {
                return ResultGenerator.genFailedResult(StringUtils.join(isAllFinish.toArray()) + "未完成，无法保存");
            }
        }

        /*String doctorPersonId = (String) resMap.get("doctorPersonId");
        String bedNo = (String) resMap.get("bedNo");
        String nurseId = (String) resMap.get("nurseId");
        String deptId = (String) resMap.get("deptId");
        String doctorPersonId = patientInHospInfo.getDoctorPersonId();
        String bedNo = patientInHospInfo.getBedNo();
        String nurseId = patientInHospInfo.getNurseId();
        String deptId = patientInHospInfo.getDeptId();*/


        //1.调用HIS接口
        //String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        //UserEntity currentUser = userMapper.selectByPrimaryKey(userId);
        //PatientInHospitalEntity patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
        //查询医生对应的emp_no,dept_code,诊断名称，诊断ICD，责任护士工号
         /*Map<String, String> res = patientInHospitalMapper.queryPatientOtherInfo(inpatNum);
        //根据用户id获取工号
        //1.调用HIS接口
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("patient_id", patientInHospitalEntity.getMedicalNum());
        param.put("visit_id", patientInHospitalEntity.getInpatTimes());
        param.put("operator", currentUser.getUserName());
        param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
        param.put("dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(deptId));
        param.put("bed_no", Integer.valueOf(bedNo));
        param.put("admission_date_time", DateUtil.dateToString(patientInHospitalEntity.getInDatetime(), "yyyy-MM-dd HH:mm:ss"));
        param.put("adm_ward_date_time", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        //param.put("cost_emp_no", userMapper.queryEmpNoById(doctorPersonId, "doctor"));
        param.put("cost_emp_no", patientInHospitalMapper.queryUserIdByPersonId(doctorPersonId));
        param.put("diagnosis", res!=null?res.get("DIAG_NAME"):"");
        param.put("diagnosis_icd", res!=null?res.get("DIAG_ICD"):"");
        //param.put("task_nurse_no", userMapper.queryEmpNoById(nurseId, "nurse"));
        param.put("task_nurse_no", patientInHospitalMapper.queryUserIdByPersonId(nurseId));
        param.put("operationID", ConstantEnum.HIS_CIRCULATION_10041.getKey());
        param.put("operating_date", "");
        param.put("operation_name", "");
        param.put("patient_condition", "");
        param.put("cell", "");
        param.put("operation_code", "");
        requestMap.put("request", param);
        map.put("c_request", requestMap);
        map.put("operationID", ConstantEnum.HIS_CIRCULATION_10041.getKey());
        log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
        System.out.println(JSON.toJSONString(map));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, map);
        if(jsonObject.isEmpty()){
            return ResultGenerator.genFailedResult("患者入院失败");
        }
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //return ResultGenerator.genFailedResult("HIS接口调用失败");
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            }
        }

        //2.保存病人信息
        patientInHospitalEntity.setResponsibleDoctorPersonId(doctorPersonId);
        patientInHospitalEntity.setBedNo(bedNo);
        patientInHospitalEntity.setInDatetime(DateUtil.dateToTimestamp(new Date()));
        //patientInHospitalEntity.setInpatTimes(patientInHospitalEntity.getInpatTimes() + 1);
        patientInHospitalEntity.setInpatTimes(patientInHospitalEntity.getInpatTimes());
        patientInHospitalEntity.setResponsibleNursePersonId(nurseId);
        patientInHospitalEntity.setDeptId(deptId);
        patientInHospitalEntity.setInDeptId(deptId);
        patientInHospitalEntity.setInWardDatetime(DateUtil.dateToTimestamp(new Date()));
        patientInHospitalEntity.setWardDeptId(wardDeptId);
        patientInHospitalMapper.updateByPrimaryKeySelective(patientInHospitalEntity);
        //3.增加责任护士对应的床号
        /*if (StringUtils.isNotEmpty(nurseId)) {
            List<NurseTeamDutyEntity> nurseTeamDutyEntityList = nurseTeamDutyMapper.selectDutyByNurseId(nurseId, wardDeptId);
            if (!nurseTeamDutyEntityList.parallelStream().anyMatch(x -> x.getBedNo().equals(bedNo))) {
                if (null != nurseTeamDutyEntityList && nurseTeamDutyEntityList.size() > 0) {
                    NurseTeamDutyEntity nurseTeamDutyEntity = nurseTeamDutyEntityList.get(0);
                    NurseTeamDutyEntity newNurseTeamDuty = new NurseTeamDutyEntity();
                    newNurseTeamDuty.initAdd();
                    newNurseTeamDuty.setTeamName(nurseTeamDutyEntity.getTeamName());
                    newNurseTeamDuty.setTeamId(nurseTeamDutyEntity.getNurseId());
                    newNurseTeamDuty.setNurseName(nurseTeamDutyEntity.getNurseName());
                    newNurseTeamDuty.setNurseId(nurseTeamDutyEntity.getNurseId());
                    newNurseTeamDuty.setIsHeader(nurseTeamDutyEntity.getIsHeader());
                    newNurseTeamDuty.setDutyId(UUIDUtil.randomString());
                    newNurseTeamDuty.setBedNo(bedNo);
                    nurseTeamDutyMapper.insert(newNurseTeamDuty);
                }
            }
        }*/
        //4.增加入院完成日志
        //CirculationLogEntity circulationLogEntity = commonTaskCirculationMapper.selectLogByInpatNumAndType(inpatNum, CirculationModelEnum.WAIT_IN_HOSP.getCode());
        /*CirculationLogEntity circulationLogEntity = circulationLogMapper.queryCirculationLogById(circulationLogId);
        if (null == circulationLogEntity) {
            return ResultGenerator.genOkResult();
        }
        circulationLogEntity.setStatus(1);
        circulationLogEntity.setOperator(userId);
        //更新入院状态
        circulationLogMapper.updateByPrimaryKeySelective(circulationLogEntity);
        //增加入院完成日志
        CirculationLogEntity inHosEntity = new CirculationLogEntity();
        inHosEntity.initAdd();
        inHosEntity.setStatus(1);
        inHosEntity.setCirculationLogId(UUIDUtil.randomString());
        inHosEntity.setCirculationModelType(CirculationModelEnum.FINISH_IN_HOSP.getCode());
        inHosEntity.setCirculationOperateType(CirculationTypeEnum.IN_HOSP.getCode());
        inHosEntity.setHealthNum(patientInHospitalEntity.getHealthNum());
        inHosEntity.setInBedNo(bedNo);
        //inHosEntity.setInDatetime(new Date());
        inHosEntity.setInDatetime(DateUtil.stringToDate(inDatetime + ":00", "yyyy-MM-dd HH:mm:ss"));
        inHosEntity.setInDeptId(deptId);
        inHosEntity.setInDoctorPersonId(doctorPersonId);
        inHosEntity.setInNurseId(nurseId);
        inHosEntity.setInpatNum(inpatNum);
        inHosEntity.setInWardDeptId(wardDeptId);
        inHosEntity.setPatTypeId(patientInHospitalEntity.getPatTypeId());
        inHosEntity.setSerialNo(null == circulationLogEntity.getSerialNo() ? 1 : circulationLogEntity.getSerialNo() + 1);
        inHosEntity.setSourceType(Constant.SELF);
        inHosEntity.setBatchNo(circulationLogEntity.getBatchNo());
        inHosEntity.setOperator(userId);
        circulationLogMapper.insert(inHosEntity);*/


        //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
        //List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(circulationLogEntity.getCirculationLogId());
        //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
        /*if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
            commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, inHosEntity.getCirculationLogId());
        }*/

        //更新床号
        //circulationLogMapper.updateBedNoStatus(bedNo,wardDeptId,"1");

        return ResultGenerator.genOkResult();
    }

    @Override
    public Result queryDepDoctorAndNursList(String depId,String id) {
        List<Map<String, String>> userList = patientInHospitalMapper.queryDepDoctorAndNursList(depId,id,null);
        return ResultGenerator.genOkResult(userList);
    }

    @Override
    public Result queryDepDoctorAndNursList2(String depId,String id,Integer page,Integer pageSize,String keyWords) {
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> userList = patientInHospitalMapper.queryDepDoctorAndNursList(depId,id,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(userList);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result saveOperator(String inpatNum, String circulationTemplateId, String emrFileId, String circulationlLogId) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        CommonTaskCirculationEntity commonTaskCirculationInfo = commonTaskCirculationMapper.selectByLogIdAndTempId(circulationlLogId, circulationTemplateId);
        if (commonTaskCirculationInfo == null) {
            CirculationTemplateEntity circulationTemplateEntity = circulationTemplateMapper.selectByPrimaryKey(circulationTemplateId);
            CommonTaskCirculationEntity commonTaskCirculationEntity = new CommonTaskCirculationEntity();
            commonTaskCirculationEntity.initAdd();
            commonTaskCirculationEntity.setCirculationTemplateId(circulationTemplateId);
            commonTaskCirculationEntity.setCommonTaskCirculationId(UUIDUtil.randomString());
            commonTaskCirculationEntity.setInpatNum(inpatNum);
            commonTaskCirculationEntity.setEmrFileId(emrFileId);
            commonTaskCirculationEntity.setSerialNo(circulationTemplateEntity.getOrderNo());
            commonTaskCirculationEntity.setExecuteUserId(userId);
            commonTaskCirculationEntity.setExecuteDatetime(new Date());
            commonTaskCirculationEntity.setCirculationlLogId(circulationlLogId);
            commonTaskCirculationMapper.insert(commonTaskCirculationEntity);
        } else {
            CirculationTemplateEntity circulationTemplateEntity = circulationTemplateMapper.selectByPrimaryKey(circulationTemplateId);
            CommonTaskCirculationEntity commonTaskCirculationEntity = new CommonTaskCirculationEntity();
            commonTaskCirculationEntity.initAdd();
            commonTaskCirculationEntity.setCirculationTemplateId(circulationTemplateId);
            commonTaskCirculationEntity.setCommonTaskCirculationId(UUIDUtil.randomString());
            commonTaskCirculationEntity.setInpatNum(inpatNum);
            commonTaskCirculationEntity.setEmrFileId(emrFileId);
            commonTaskCirculationEntity.setSerialNo(circulationTemplateEntity.getOrderNo());
            commonTaskCirculationEntity.setExecuteUserId(userId);
            commonTaskCirculationEntity.setExecuteDatetime(new Date());
            commonTaskCirculationEntity.setCirculationlLogId(circulationlLogId);
            commonTaskCirculationEntity.setCommonTaskCirculationId(commonTaskCirculationInfo.getCommonTaskCirculationId());
            commonTaskCirculationMapper.updateByPrimaryKey(commonTaskCirculationEntity);
        }
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result cancleInHosp(String inpatNum,String circulationLogId){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //判断是否产生费用，是否有医嘱
        Map cost = queryPatientCost(inpatNum);
        PatientInHospitalEntity patientInHospitalEntity = (PatientInHospitalEntity) cost.get("patientInfo");
        String totalCost = StringUtils.isEmpty((String) cost.get("TOTAL_COST")) ? "0" : (String) cost.get("TOTAL_COST");
        if (Double.parseDouble(totalCost) != 0)
            return ResultGenerator.genFailedResult("已产生余额，无法取消入院");
        if (circulationLogMapper.selectIsOrderActive(inpatNum) != 0)
            return ResultGenerator.genFailedResult("已存在下达医嘱，无法取消入院");

        CirculationLogEntity inCirculationLogEntity=null;
        if(StringUtils.isNotBlank(circulationLogId)){
            inCirculationLogEntity = circulationLogMapper.selectNewLogByInpatNum(inpatNum,circulationLogId);
        }

        //取消新入科接口 10036
        Map<String, Object> param = new HashMap<>();
        //病人编码 住院号
        param.put("p_patient_id", patientInHospitalEntity.getMedicalNum());
        //就诊次数 住院号-后的值
        param.put("p_visit_id", patientInHospitalEntity.getInpatTimes());
        //床号
        param.put("p_bed_no", patientInHospitalEntity.getBedNo());
        //原病区代码
        param.put("p_ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(patientInHospitalEntity.getWardDeptId()));
        //原科室代码
        param.put("p_dept_code_in", patientInHospitalMapper.queryDeptCodeByDeptId(patientInHospitalEntity.getDeptId()));
        //取消转出科室操作码
        param.put("operationID", ConstantEnum.HIS_CIRCULATION_10045.getKey());

        System.out.println(JSON.toJSONString(param));

        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
        if (jsonObject.isEmpty()) {
            return ResultGenerator.genFailedResult("患者取消入院失败");
        }
        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
        if (resInt < 0) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //return ResultGenerator.genFailedResult("HIS接口调用失败");
            return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
        }
        //更新已入院标记
        if(StringUtils.isNotBlank(circulationLogId)) {
            circulationLogMapper.updateCancleFlagOutHosp(inCirculationLogEntity.getCirculationLogId(), userId);
        }else{
            List<CirculationLogEntity> circulationLogEntities = circulationLogMapper.selectInHospLogByInpatNum(inpatNum);
            if(CollectionUtils.isNotEmpty(circulationLogEntities)){
                circulationLogMapper.updateCancleFlagOutHosp(circulationLogEntities.get(0).getCirculationLogId(), userId);
            }
        }
        String bedLabel = circulationLogMapper.queryBedLabel(patientInHospitalEntity.getInWardDeptId(), patientInHospitalEntity.getBedNo());
        //增加取消入院日志
        CirculationLogEntity circulationLogEntity = new CirculationLogEntity();
        circulationLogEntity.initAdd();
        circulationLogEntity.setStatus(1);
        circulationLogEntity.setCirculationLogId(UUIDUtil.randomString());
        circulationLogEntity.setCirculationModelType(CirculationModelEnum.CANCLE_IN_HOSP.getCode());
        circulationLogEntity.setCirculationOperateType(CirculationTypeEnum.IN_HOSP.getCode());
        circulationLogEntity.setHealthNum(patientInHospitalEntity.getHealthNum());
        circulationLogEntity.setInDeptId(patientInHospitalEntity.getInDeptId());
        circulationLogEntity.setInDoctorPersonId(patientInHospitalEntity.getResponsibleDoctorPersonId());
        circulationLogEntity.setInpatNum(patientInHospitalEntity.getInpatNum());
        circulationLogEntity.setInWardDeptId(patientInHospitalEntity.getInWardDeptId());
        circulationLogEntity.setPatTypeId(patientInHospitalEntity.getPatTypeId());
        circulationLogEntity.setSourceType(Constant.SELF);
        circulationLogEntity.setInBedNo(patientInHospitalEntity.getBedNo());
        circulationLogEntity.setInBedLabel(bedLabel);
        circulationLogEntity.setOperator(userId);
        Integer newSerialNo = null;
        if (null != inCirculationLogEntity) {
            circulationLogEntity.setSerialNo(inCirculationLogEntity.getSerialNo() + 1);
            newSerialNo = circulationLogEntity.getSerialNo();
            circulationLogEntity.setInDatetime(inCirculationLogEntity.getInDatetime());
            circulationLogEntity.setBatchNo(inCirculationLogEntity.getBatchNo());
            circulationLogEntity.setInNurseId(inCirculationLogEntity.getInNurseId());
        }else{
            circulationLogEntity.setSerialNo(1);
            newSerialNo = circulationLogEntity.getSerialNo();
            circulationLogEntity.setInDatetime(patientInHospitalEntity.getInDatetime());
            circulationLogEntity.setBatchNo(1);
            Map<String, String> patientInfo = circulationLogMapper.queryDeptByInpatNum(inpatNum);
            if(patientInfo!=null){
                circulationLogEntity.setInNurseId(patientInfo.get("nurseId"));
            }

        }

        circulationLogMapper.insert(circulationLogEntity);
        //更改病人信息为待转入，增加待转入日志
        circulationLogEntity = new CirculationLogEntity();
        circulationLogEntity.initAdd();
        circulationLogEntity.setStatus(0);
        circulationLogEntity.setCirculationLogId(UUIDUtil.randomString());
        circulationLogEntity.setCirculationModelType(CirculationModelEnum.WAIT_IN_HOSP.getCode());
        circulationLogEntity.setCirculationOperateType(CirculationTypeEnum.IN_HOSP.getCode());
        circulationLogEntity.setHealthNum(patientInHospitalEntity.getHealthNum());
        circulationLogEntity.setInpatNum(patientInHospitalEntity.getInpatNum());
        circulationLogEntity.setInWardDeptId(patientInHospitalEntity.getInWardDeptId());
        circulationLogEntity.setPatTypeId(patientInHospitalEntity.getPatTypeId());
        circulationLogEntity.setSourceType(Constant.SELF);
        //circulationLogEntity.setInBedNo(patientInHospitalEntity.getBedNo());
        if (null != inCirculationLogEntity) {
            circulationLogEntity.setSerialNo(newSerialNo == null ? 1 : (newSerialNo + 1));
            circulationLogEntity.setBatchNo(inCirculationLogEntity.getBatchNo());
        }else{
            circulationLogEntity.setSerialNo(newSerialNo == null ? 1 : (newSerialNo + 1));
            circulationLogEntity.setBatchNo(1);
        }
        circulationLogEntity.setOperator(userId);
        circulationLogMapper.insert(circulationLogEntity);

        //patientInHospitalEntity.setInWardDatetime(null);
        //patientInHospitalEntity.setResponsibleDoctorPersonId(null);
        //patientInHospitalEntity.setBedNo(null);
        //patientInHospitalEntity.setInDatetime(DateUtil.dateToTimestamp(new Date()));
        //patientInHospitalEntity.setInDatetime(null);
        //patientInHospitalEntity.setInpatTimes(patientInHospitalEntity.getInpatTimes() == 0 ? 0 : patientInHospitalEntity.getInpatTimes() - 1);
        //patientInHospitalEntity.setInpatTimes(patientInHospitalEntity.getInpatTimes());
        //patientInHospitalEntity.setResponsibleNursePersonId(null);
        //patientInHospitalEntity.setDeptId(null);
        //patientInHospitalEntity.setInDeptId(null);
        //patientInHospitalEntity.setWardDeptId(null);
        //patientInHospitalMapper.updateByPrimaryKeySelective(patientInHospitalEntity);
        circulationLogMapper.cancelUpdateInHospPatient(inpatNum);
        circulationLogMapper.cancelUpdateInHospNurse(inpatNum);
        //删除

        //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
        if(StringUtils.isNotBlank(circulationLogId)) {
            List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(inCirculationLogEntity.getCirculationLogId());
            //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
            if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, circulationLogEntity.getCirculationLogId());
            }
        }

        //更新床号
        circulationLogMapper.updateBedNoStatus(patientInHospitalEntity.getBedNo(), patientInHospitalEntity.getWardDeptId(), "0");

        return ResultGenerator.genOkResult();
    }

    @Override
    public Result queryPatientCirculationDetailByInpatNum(String inpatNum) {
        InHospitalPatientVO inHospitalPatientVO = patientInHospitalMapper.queryPatientCirculationDetailByInpatNum(inpatNum);
        //费别 注释的是正式参数与返回
        String url = cost;
        Map<String, Object> param = new HashMap<>();
        param.put("as_patientId", inpatNum.replace("-1", ""));
        param.put("operationID", "10001");
        param.put("al_visitId", "1");
        param.put("al_doctor_type", "");

        CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
                HttpClientUtil.sendPost(url, param)).thenApply(x -> x.toString());
        try {
            JSONObject jsonObject = JSON.parseObject(ordedCustomerFuture.get());
            if (jsonObject.getString("data") != null) {
                Map cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                if (cost.get("CHARGE_TYPE").toString().contains("自费")) {
                    inHospitalPatientVO.setPayOff("自费");
                } else {
                    inHospitalPatientVO.setPayOff(cost.get("CHARGE_TYPE").toString());
                }
            }
        } catch (Exception e) {
            log.error("查询费用明细失败", e);
        }
        return ResultGenerator.genOkResult(inHospitalPatientVO);
    }

    private Map queryPatientCost(String inpatNum) {
        PatientInHospitalEntity patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
        //费别
        String url = cost;
        Map<String, Object> param = new HashMap<>();
        param.put("as_patientId", patientInHospitalEntity.getMedicalNum());
        param.put("operationID", "10001");
        param.put("al_visitId", "1");
        param.put("al_doctor_type", "");
        Map cost = new CopyOnWriteMap();
        try {
            JSONObject jsonObject = HttpClientUtil.sendPost(url, param);
            if (jsonObject.getString("data") != null) {
                cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
            }
        } catch (Exception e) {
            log.error("查询费用明细失败", e);
        }
        cost.put("patientInfo", patientInHospitalEntity);
        return cost;
    }

    /**
     * 判断该病人是否出院结清费用
     *
     * @param inpatNum
     * @param inpatTimes
     * @return
     */
    public boolean queryPatientSettlement(String inpatNum, Integer inpatTimes) {
        Map<String, String> patientMap = new HashMap<String, String>();
        //费别
        Map<String, Object> param = new HashMap<>();
        param.put("p_patient_id", inpatNum);
        param.put("p_visit_id", inpatTimes);
        param.put("operationID", "10023");
        Map cost = null;
        try {
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
            if (jsonObject.getString("data") != null) {
                cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                if ("未结账".equals(cost.get("JZZT"))) {
                    return false;
                } else if ("已结账".equals(cost.get("JZZT"))) {
                    return true;
                }
            }

        } catch (Exception e) {
            log.error("查询费用明细失败", e);
        }
        return false;
    }


    @Override
    public Result patientGoOut(String inpatNum, String time, String reason) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<Map<String, String>> back = circulationLogMapper.getRotatingList(inpatNum, StateEnum.INCOMPLETE.getValue(), null, CirculationModelEnum.FINISH_IN.getCode(), null, null);
        if (back != null && back.size() > 0) {
            return ResultGenerator.genFailedResult("病人未回归,不可操作");
        }
        Map<String, String> patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, null);
        int v = 0;
        if (StringUtils.isNotBlank(patient.get("visitId"))) {
            v = Integer.parseInt(patient.get("visitId"));
        }

        boolean flag = queryPatientSettlement(inpatNum.replaceAll("-1", ""), v);
        if (flag) {
            return ResultGenerator.genFailedResult("病人已出院,不可操作");
        }

        Map<String, String> patientInfo = patientInHospitalMapper.getPatientInfo(inpatNum);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (Exception e) {
            log.error("时间转换错误");
        }
//        circulationLogMapper.updateLogStatusById(back.get(0).get("CIRCULATION_LOG_ID"), null,sdf.format(new Date()), StateEnum.COMPLETED.getValue());

        CirculationLogEntity entity = new CirculationLogEntity();//外出日志
        entity.initAdd();
        entity.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));//1已完成
        entity.setCirculationLogId(UUIDUtil.randomString());
        entity.setCirculationModelType(CirculationModelEnum.FINISH_OUT.getCode());
        entity.setCirculationOperateType(CirculationTypeEnum.OUT_IN.getCode());
        entity.setHealthNum(patientInfo.get("healthNum"));
        entity.setInpatNum(inpatNum);
        entity.setOutDatetime(new Timestamp(date.getTime()));
        entity.setRemark(reason);
        entity.setSourceType("SELF");
        entity.setSerialNo(1);
        entity.setOperator(userId);
        circulationLogMapper.insert(entity);
        CirculationLogEntity entity2 = new CirculationLogEntity();//外出日志
        entity2.initAdd();
        entity2.setStatus(Integer.parseInt(StateEnum.INCOMPLETE.getValue()));//0未完成
        entity2.setCirculationLogId(UUIDUtil.randomString());
        entity2.setCirculationModelType(CirculationModelEnum.FINISH_IN.getCode());
        entity2.setCirculationOperateType(CirculationTypeEnum.OUT_IN.getCode());
        entity2.setHealthNum(patientInfo.get("healthNum"));
        entity2.setInpatNum(inpatNum);
        entity2.setOutDatetime(new Timestamp(date.getTime()));
        entity2.setRemark(reason);
        entity2.setSourceType("SELF");
        entity2.setSerialNo(1);
        entity2.setOperator(userId);
        circulationLogMapper.insert(entity2);
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result patientRegression(String inpatNum, String time) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<Map<String, String>> back = circulationLogMapper.getRotatingList(inpatNum, StateEnum.INCOMPLETE.getValue(), null, CirculationModelEnum.FINISH_IN.getCode(), null, null);
        if (back == null || back.size() <= 0) {
            return ResultGenerator.genFailedResult("病人无待回归记录,不可操作");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date out = new Date();
        try {
            out = sdf.parse(back.get(0).get("outTime"));
            Date in = sdf.parse(time);
            if (in.getTime() <= out.getTime())
                return ResultGenerator.genFailedResult("回归时间不能小于外出时间");
        } catch (Exception e) {
        }
        circulationLogMapper.updateLogStatusById(back.get(0).get("CIRCULATION_LOG_ID"), sdf.format(new Date()), null, StateEnum.COMPLETED.getValue(),userId);
        return ResultGenerator.genOkResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result patientRotating(String inpatNum,String circulationLogId) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<Map<String, String>> rotatingList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.INCOMPLETE.getValue(), null, CirculationModelEnum.WAIT_ROTATING_BED.getCode(), null, circulationLogId);//获取待转床日志
        try {
            if (rotatingList == null || rotatingList.size() <= 0)
                return ResultGenerator.genFailedResult("此病人无待转床");
            Map<String, String> patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, rotatingList.get(0).get("CIRCULATION_LOG_ID"));
            for (Map<String, String> rotating : rotatingList) {
                String turnBed = rotating.get("IN_BED_NO");
                boolean flag = true;
                List<String> list = commonTaskCirculationMapper.queryBedByWardDeptId(patient.get("wardDeptId"));
                for (String bed : list) {
                    if (bed.equals(turnBed)) {
                        flag = false;
                    }
                }
                if (flag)
                    return ResultGenerator.genFailedResult("当前床位不可转入");

                //his start
                //调用转床his接口
                Map<String, Object> param = new HashMap<>();
                //病人编码 住院号
                param.put("p_patient_id", patient.get("medicalNum"));
                //就诊次数 住院号-后的值
                param.put("p_visit_id", patient.get("inpatTimes"));
                //原床病人编码
                param.put("p_patient_id_old", "");
                //原床病人就诊次数
                param.put("p_visit_id_old", "");
                //原床号码
                param.put("p_bed_no_old", rotatingList.get(0).get("OUT_BED_NO"));
                //新床号码
                param.put("p_bed_no_new", rotatingList.get(0).get("IN_BED_NO"));
                //病区代码
                param.put("p_WardCode", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("OUT_WARD_DEPT_ID")));
                //转出科室操作码
                param.put("operationID", ConstantEnum.HIS_CIRCULATION_10033.getKey());
                System.out.println(JSON.toJSONString(param));
                JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
                if (jsonObject.isEmpty()) {
                    return ResultGenerator.genFailedResult("患者转床失败");
                }
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    //return ResultGenerator.genFailedResult("HIS接口调用失败");
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }

                //his end

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                circulationLogMapper.updateLogStatusById(rotating.get("CIRCULATION_LOG_ID"), sdf.format(new Date()), null, StateEnum.COMPLETED.getValue(),userId);//更新病人转床日志状态
                circulationLogMapper.updatePatient(inpatNum, turnBed, null, null, null, null);//更新病人住院信息床号

                CirculationLogEntity entity2 = new CirculationLogEntity();//已转床日志
                entity2.initAdd();
                entity2.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));//已完成
                entity2.setCirculationLogId(UUIDUtil.randomString());
                entity2.setCirculationModelType(CirculationModelEnum.FINISH_ROTATING_BED.getCode());
                entity2.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_BED.getCode());
                entity2.setInpatNum(inpatNum);
                String outTime = rotating.get("outTime");
                if (StringUtils.isBlank(outTime))
                    outTime = sdf.format(new Date());
                entity2.setOutDatetime(new Timestamp(sdf.parse(outTime).getTime()));
                entity2.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity2.setOutWardDeptId(rotating.get("OUT_WARD_DEPT_ID"));
                entity2.setInDatetime(new Date());
                entity2.setInBedNo(rotating.get("IN_BED_NO"));
                entity2.setInBedLabel(circulationLogMapper.queryBedLabel(rotating.get("IN_WARD_DEPT_ID"),rotating.get("IN_BED_NO")));
                entity2.setOutBedNo(rotating.get("OUT_BED_NO"));
                entity2.setOutBedLabel(rotating.get("OUT_BED_LABEL"));
                entity2.setSourceType("SELF");

                entity2.setCancelFlag(0);
                if (rotating.get("BATCH_NO") != null || rotating.get("BATCH_NO") != "") {
                    entity2.setBatchNo(Integer.parseInt(String.valueOf(rotating.get("BATCH_NO"))));
                } else {
                    entity2.setBatchNo(1);
                }
                entity2.setInDeptId(rotating.get("IN_DEPT_ID"));
                entity2.setOutDeptId(rotating.get("OUT_DEPT_ID"));
                entity2.setPatTypeId(rotating.get("PAT_TYPE_ID"));
                entity2.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
                entity2.setHealthNum(rotating.get("HEALTH_NUM"));
                entity2.setOutDoctorPersonId(rotating.get("OUT_DOCTOR_PERSON_ID"));
                entity2.setOutNurseId(rotating.get("OUT_NURSE_ID"));
                entity2.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                entity2.setInNurseId(rotating.get("IN_NURSE_ID"));
                //获取医生信息
                /*String doctorPersonId = circulationLogMapper.queryPatientInHospitalByInpatNum(inpatNum);
                if (StringUtils.isNotBlank(doctorPersonId)) {
                    entity2.setInDoctorPersonId(doctorPersonId);
                } else {
                    entity2.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                }*/

                //entity2.setSerialNo(1);
                entity2.setSerialNo(rotating.get("serialNo") == null ? 1 : (Integer.parseInt(rotating.get("serialNo"))) + 1);
                entity2.setOperator(userId);
                circulationLogMapper.insert(entity2);

                //更新床号 原床状态为0
                circulationLogMapper.updateBedNoStatus(rotatingList.get(0).get("OUT_BED_NO"), rotatingList.get(0).get("OUT_WARD_DEPT_ID"), "0");
                //新床状态为1
                circulationLogMapper.updateBedNoStatus(rotatingList.get(0).get("IN_BED_NO"), rotatingList.get(0).get("OUT_WARD_DEPT_ID"), "1");

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转床失败" + e.getMessage());
            return ResultGenerator.genFailedResult("转床失败");
        }

        //等待请求his todo

        return ResultGenerator.genOkResult();
    }

    @Override
    public Result rotatingHistory(String inpatNum, String circulationlLogId) {
        List<Map<String, String>> list = circulationLogMapper.getRotatingList(inpatNum, StateEnum.COMPLETED.getValue(),
                CirculationTypeEnum.TRANSFERRED_BED.getCode(), CirculationModelEnum.FINISH_ROTATING_BED.getCode(), null, circulationlLogId);
        Map<String, String> patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, circulationlLogId);

        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, String> item : list) {
            Map<String, Object> res = new HashMap<>();
            res.put("inTime", item.get("inTime"));
            res.put("patient", patient);
            result.add(res);
        }
        return ResultGenerator.genOkResult(result);
    }

    @Override
    public Result getPatientList(List<String> circulationType,
                                 String status, String endDate, String startDate,
                                 String keyWords, String inWardDeptId, String outWardDeptId, String wardDeptId) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<String> circulationModel = new ArrayList<String>();
        if (StateEnum.INCOMPLETE.getValue().equals(status)) {
            circulationModel = circulationType.stream().filter(ct -> ct.indexOf("wait_") == 0).collect(Collectors.toList());
        } else if (StateEnum.COMPLETED.getValue().equals(status)) {
            circulationModel = circulationType.stream().filter(ct -> ct.indexOf("finish_") == 0).collect(Collectors.toList());
        }
        //用来对查询结果进行筛选
        String screeningCondition = null;
        String wardDeptName = null;
        String deptArea = null;

        if (StringUtils.isNotBlank(wardDeptId)) {
            SysDeptDictEntity sysDeptDictEntity = sysDeptDictMapper.selectByPrimaryKey(wardDeptId);
            //if (null != dictDTO) {
            if (null != sysDeptDictEntity) {
                String deptName = sysDeptDictEntity.getDeptName();
                deptArea = sysDeptDictEntity.getDeptArea();

                if (deptName.contains("手术室护理单元")) {
                    //手术科室，只查询手术室转入、转出相关信息
                    circulationModel = circulationModel.stream().filter(ct -> ct.indexOf("_operation") > 0)
                            .collect(Collectors.toList());
                    wardDeptId = "";
                    screeningCondition = "operation";
                } else if (deptName.contains("麻醉护理单元")) {
                    //复苏科室，只查询复苏室转入、转出相关信息
                    circulationModel = circulationModel.stream().filter(ct -> ct.indexOf("_resuscitation") > 0)
                            .collect(Collectors.toList());
                    wardDeptId = "";
                    screeningCondition = "resuscitation";
                } else {
                    //普通科室，查询不包含手术、复苏科室的信息
                    List<String> operations = circulationModel.stream().filter(ct -> ct.indexOf("_operation") > 0).collect(Collectors.toList());
                    List<String> resuscitations = circulationModel.stream().filter(ct -> ct.indexOf("_resuscitation") > 0).collect(Collectors.toList());
                    circulationModel.removeAll(operations);
                    circulationModel.removeAll(resuscitations);
                }


            }
        }
        List<String> types = circulationLogMapper.getModelTypes(circulationModel, status, endDate, startDate, keyWords, inWardDeptId, outWardDeptId, wardDeptId);
        List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
        for (String type : types) {
            Map map = new HashMap();
            List oneTimes = new ArrayList();
            List<Map<String, String>> result = circulationLogMapper.getPatientList(circulationModel, status, endDate, startDate, keyWords, inWardDeptId, outWardDeptId, type, wardDeptId, deptArea);
            //把his完成出院的进行过滤
            if(CirculationModelEnum.WAIT_OUT_HOSP.getCode().equals(type) || CirculationModelEnum.WAIT_ROTATING_BED.getCode().equals(type)
                    || CirculationModelEnum.WAIT_IN_DEPT.getCode().equals(type) || CirculationModelEnum.WAIT_OUT_HOSP.getCode().equals(type)
                    || CirculationModelEnum.WAIT_IN_RESUSCITATION.getCode().equals(type) || CirculationModelEnum.WAIT_OUT_RESUSCITATION.getCode().equals(type)
                    || CirculationModelEnum.WAIT_IN_OPERATION.getCode().equals(type) || CirculationModelEnum.WAIT_IN_OPERATION.getCode().equals(type)
                    || CirculationModelEnum.WAIT_IN_WARD.getCode().equals(type) || CirculationModelEnum.WAIT_OUT_WARD.getCode().equals(type)){
                if(CollectionUtils.isNotEmpty(result)){
                    List<String> ids = new CopyOnWriteArrayList<>();
                    for (Map<String, String> item : result) {
                        if(StringUtils.isNotBlank(item.get("patientOutHospDateTime")) && (StringUtils.isBlank(item.get("currentBedNo")) || "0".equals(item.get("currentBedNo")))){
                            ids.add(item.get("circulationLogId"));
                        }
                    }
                    if(CollectionUtils.isNotEmpty(ids)){
                        circulationLogMapper.updateCancleFlag(ids,userId);
                    }
                }
                result = result.stream().filter(x -> !(StringUtils.isNotBlank(x.get("patientOutHospDateTime")) && (StringUtils.isBlank(x.get("currentBedNo")) || "0".equals(x.get("currentBedNo"))))).collect(Collectors.toList());
            }
            for (Map<String, String> item : result) {
                if (StringUtils.isBlank(item.get("wardName"))) {
                    continue;
                }
                int ind = item.get("wardName").indexOf("护理单元");
                if (ind > 0) {
                    item.put("wardName", item.get("wardName").substring(0, ind));
                }
            }
            if (type != null) {
                map.put("type", type);
            } else {
                map.put("type", "无");
            }
            map.put("patients", result);
            map.put("typeFlag", getCirculationModelTypeFlag(type));
            res.add(map);
        }

        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        //手术信息
        circulationModel.stream().forEach(cm -> {
            Map<String, Object> map = res.stream().filter(re -> cm.equals(re.get("type").toString())).findFirst().orElse(null);
            if (map != null) {
                resultList.add(map);
            } else {
                Map<String, Object> nullMap = new HashMap<String, Object>();
                nullMap.put("type", cm);
                nullMap.put("typeFlag", getCirculationModelTypeFlag(cm));
                nullMap.computeIfAbsent("patients", k -> new ArrayList<>());
                resultList.add(nullMap);
            }
        });
        //过滤手术待转出数据
        if (CollectionUtils.isNotEmpty(resultList)) {
            //获取系统时间
            String prevTime = DateUtil.dateToString(DateUtil.getDateBefore(new Date(),0),"yyyy-MM-dd");
            for (Map<String, Object> map : resultList) {
                if (CirculationModelEnum.WAIT_OUT_WARD.getCode().equals((String) map.get("type"))) {
                    List<Map<String, String>> patientsList = (List<Map<String, String>>) map.get("patients");

                    List<Map<String, String>> patientsNewList = new ArrayList<Map<String, String>>();
                    if (CollectionUtils.isNotEmpty(patientsList)) {
                        for (Map<String, String> pat : patientsList) {
                            CirculationLogDTO circulationLogEntity = circulationLogMapper.queryDtoCirculationLogById(pat.get("circulationLogId"));
                            Map<String, String> operation = circulationLogMapper.queryPatientOperationByInpatorderdataId(circulationLogEntity.getInpatorderdataId());
                            String operationTime = circulationLogMapper.queryOperationTime(circulationLogEntity.getInpatorderdataId());
                            System.out.println(operationTime);
                            if(StringUtils.isNotBlank(operationTime) && prevTime.compareTo(operationTime.substring(0,10))<=0){
                                String visitId = pat.get("inpatNum").split("-")[1];
                                //his对接
                                Map<String, Object> param = new HashMap<>();
                                //病人编码 住院号
                                param.put("p_patient_id", pat.get("medicalNum"));
                                //就诊次数 住院号-后的值
                                param.put("p_visit_id", visitId);
                                //排序字段及方向
                                param.put("p_sort", "");
                                //当前页-默认第一页
                                param.put("p_curPage", "1");
                                //每页行数-默认每页10行
                                param.put("p_pageSize", "10");
                                //手术操作码
                                param.put("operationID", ConstantEnum.HIS_CIRCULATION_10046.getKey());
                                System.out.println(JSON.toJSONString(param));

                                JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
                                if (jsonObject.isEmpty()) {
                                    //return ResultGenerator.genFailedResult("手术获取数据失败");
                                }
                                Integer resInt = Integer.valueOf((String) jsonObject.get("p_totalRecords"));
                                if (resInt < 0) {
                                    //return ResultGenerator.genFailedResult("HIS接口调用失败");
                                    //return ResultGenerator.genFailedResult("手术获取数据失败");
                                }
                                if (jsonObject.getString("data") != null) {
                                    List<Map> list = JSONArray.parseArray(jsonObject.getString("data"), Map.class);
                                    if (list != null && list.size() > 0) {
                                        for (Map oMap : list) {
                                            if (CommonUtils.isNotEmpty((String) oMap.get("OPERATING_ROOM_NO")) && CommonUtils.isNotEmpty((String) oMap.get("ARRANGE_DATE_TIME"))) {
                                                if ((oMap.get("OPERATION")).equals(operation.get("operationName")) && operationTime.equals(oMap.get("SCHEDULED_DATE_TIME"))) {
                                                    patientsNewList.add(pat);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                    map.put("patients", patientsNewList);
                }
            }
        }

        return ResultGenerator.genOkResult(resultList);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result patientLeaveHospital(String inpatNum, String dischanargeModeName, String dischanargeModeCode, String medicalCategory,
                                       String medicalCategoryCode, String outDatetime,String diagId,
                                       String circulationLogId,String stopDateTime,String babyStopDateTime) {

        try {
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            //验证是否必填资料是否全部完成
            /*List<String> isAllFinish = circulationTemplateMapper.checkIsFinish(inpatNum, "out_hosp");
            if (null != isAllFinish && isAllFinish.size() > 0) {
                return ResultGenerator.genFailedResult(StringUtils.join(isAllFinish.toArray()) + "未完成，无法保存");
            }*/

            Date currentDate = new Date();
            //获取病人信息
            PatientInHospitalEntity patientInHospitalInfo = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
            if (patientInHospitalInfo == null) {
                return ResultGenerator.genFailedResult("此病人没住院信息");
            }
            //获取待出院信息
            CirculationLogEntity patientToBeLeaveHospital = circulationLogMapper.getWaitOutHosp(inpatNum,circulationLogId);

            //根据住院号和CIRCULATION_OPERATE_TYPE='out_hosp'和CIRCULATION_MODEL_TYPE='wait_out_hosp'查询待出院信息  把待出院的信息的状态Status设置成1
            if (patientToBeLeaveHospital == null) {
                return ResultGenerator.genFailedResult("此病人无待出院信息");
            }

            String waitCirculationLogId = patientToBeLeaveHospital.getCirculationLogId();
            String bedNo = patientToBeLeaveHospital.getOutBedNo();
            String outWardDeptId = patientToBeLeaveHospital.getOutWardDeptId();

            //获取出院诊断
//            Map<String, String> diagnsisMap = circulationLogMapper.queryDischargeDiagnosisByInpatNum(inpatNum); 改为获取his的,故注释
            if (StringUtils.isBlank(diagId)) {
                return ResultGenerator.genFailedResult("此病人无出院诊断信息");
            }

            //获取诊断icd
            Map<String, String> diagMap = circulationLogMapper.queryDiagInfoByDiagId(diagId);
            String diagName = "";
            String diagIcd = "";
            if(diagMap!=null){
                diagName=diagMap.get("diagName");
                diagIcd=diagMap.get("diagIcd");
            }

            String lastStopDateTime="";
            if(StringUtils.isNotBlank(stopDateTime)){
                //lastStopDateTime=stopDateTime;
                lastStopDateTime=stopDateTime+":00";
            }else if(StringUtils.isNotBlank(babyStopDateTime)){
                //lastStopDateTime=babyStopDateTime;
                lastStopDateTime=babyStopDateTime+":00";
            }

            //获取出院方式
            Map<String, Object> param = new HashMap<>();
            outDatetime = outDatetime + ":00";
            //病人编码 住院号
            param.put("p_patient_id", patientInHospitalInfo.getMedicalNum());
            //就诊次数 住院号-后的值
            param.put("p_visit_id", patientInHospitalInfo.getInpatTimes());
            //床号
            param.put("p_bed_no", patientToBeLeaveHospital.getOutBedNo());
            //原病区代码
            param.put("p_ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(patientToBeLeaveHospital.getOutWardDeptId()));
            //原科室代码
            param.put("p_dept_code_in", patientInHospitalMapper.queryDeptCodeByDeptId(patientToBeLeaveHospital.getOutDeptId()));
            //出院时间
            param.put("p_discharge_date_time", outDatetime);
            //出院操作码
            param.put("operationID", ConstantEnum.HIS_CIRCULATION_10038.getKey());
            //出院方式
            param.put("p_discharge_disposition", dischanargeModeCode);
            //出院诊断
            param.put("p_discharge_diag_name", diagName);
            //出院诊断代码
            param.put("p_discharge_diag_code", diagIcd);
            //出院医疗类别
            param.put("p_discharge_yllb", medicalCategoryCode);
            //一键停止时间
            param.put("p_stop_date_time", lastStopDateTime);

            System.out.println(JSON.toJSONString(param));

            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
            if (jsonObject.isEmpty()) {
                return ResultGenerator.genFailedResult("患者出院失败");
            }
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //return ResultGenerator.genFailedResult("HIS接口调用失败");
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            }

            circulationLogMapper.updateWaitOutHosp(circulationLogId,userId);
            //在CIRCULATION_LOG表中新增一条记录 CIRCULATION_MODEL_TYPE='finish_out_hosp'
            patientToBeLeaveHospital.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));
            patientToBeLeaveHospital.setCirculationModelType(CirculationModelEnum.FINISH_OUT_HOSP.getCode());
            patientToBeLeaveHospital.setSerialNo(patientToBeLeaveHospital.getSerialNo() == null ? 1 : patientToBeLeaveHospital.getSerialNo() + 1);

            Timestamp currentTime = new Timestamp(currentDate.getTime());
            patientToBeLeaveHospital.setCreateTime(currentTime);
            patientToBeLeaveHospital.setModifyTime(currentTime);
            //转出日期时间未系统时间
            //patientToBeLeaveHospital.setOutDatetime(currentTime);
            patientToBeLeaveHospital.setOutDatetime(DateUtil.stringToTimestamp(outDatetime));
            patientToBeLeaveHospital.setCirculationLogId(UUIDUtil.randomString());
            //批次
            patientToBeLeaveHospital.setBatchNo(patientToBeLeaveHospital.getBatchNo());
            //删除标记为0
            patientToBeLeaveHospital.setCancelFlag(0);
            patientToBeLeaveHospital.setSourceType("SELF");

            //设置remark
            Map<String, Object> remarkMap = new HashMap<>();
            remarkMap.put("dischanargeMode", dischanargeModeName);
            remarkMap.put("medicalCategory", medicalCategory);
            remarkMap.put("diagName", diagName);
            String remark = JSON.toJSONString(remarkMap);
            patientToBeLeaveHospital.setRemark(remark);
            patientToBeLeaveHospital.setOperator(userId);
            //patientToBeLeaveHospital.setOutBedLabel(circulationLogMapper.queryBedLabel(patientToBeLeaveHospital.getOutWardDeptId(),patientToBeLeaveHospital.getOutBedNo()));

            circulationLogMapper.insert(patientToBeLeaveHospital);
            // 修改病人信息表中的出院相关信息
            PatientInHospitalEntity patientInHospitalEntity = new PatientInHospitalEntity();
            patientInHospitalEntity.setInpatNum(inpatNum);
            patientInHospitalEntity = patientInHospitalMapper.selectOne(patientInHospitalEntity);
            if (patientInHospitalEntity != null) {
                //设置出院时间、出院科室代码、出院病区、出院病房
                //patientInHospitalEntity.setOutDatetime(currentTime);
                patientInHospitalEntity.setOutDatetime(DateUtil.stringToTimestamp(outDatetime));
                patientInHospitalEntity.setOutDeptId(patientInHospitalEntity.getDeptId());
                patientInHospitalEntity.setOutWardDeptId(patientInHospitalEntity.getWardDeptId());
                patientInHospitalEntity.setOutRoomNo(patientInHospitalEntity.getWardRoomNo());
                patientInHospitalEntity.setBedNo(null);
                //设置OUT_DEPT_ID
                patientInHospitalEntity.setGmtModify(currentTime);
                //实际住院天数
                patientInHospitalMapper.updateByPrimaryKey(patientInHospitalEntity);
            }

            //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
            List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(waitCirculationLogId);
            //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
            if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, patientToBeLeaveHospital.getCirculationLogId());
            }

            //更新床位状态
            circulationLogMapper.updateBedNoStatus(bedNo, outWardDeptId, "0");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.genOkResult();
    }

    /**
     * 获取出院方式
     *
     * @return
     */
    public Result queryDischargeMode(String id) {
        List<Map<String, String>> data =new CopyOnWriteArrayList<>();
        List<Map<String, String>> resultList =new CopyOnWriteArrayList<>();
        Map<String, Object> param = new HashMap<>();
        param.put("operationID", ConstantEnum.HIS_CIRCULATION_10042.getKey());
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
        if (null != jsonObject) {
            if (jsonObject.getString("data") != null) {
                data = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {});
                if(CollectionUtils.isNotEmpty(data)){
                    data.parallelStream().forEachOrdered(x->{
                        if(!(StringUtils.isNotBlank(id) && id.equals(x.get("DISCHARGE_DISPOSITION_CODE")))){
                            x.put("id",x.get("DISCHARGE_DISPOSITION_CODE"));
                            x.put("name",x.get("DISCHARGE_DISPOSITION_NAME"));
                            resultList.add(x);
                        }
                    });
                }
            }
        }
        return ResultGenerator.genOkResult(resultList);
    }

    /**
     * 获取医疗类别
     *
     * @return
     */
    public Result queryMedicalCategory(String inpatNum) {
        List<Map<String, Object>> yllbList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();
        param.put("patient_id", inpatNum.split("-")[0]);
        param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));

        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("request", param);
        Map<String, Object> params = new HashMap<>();
        params.put("c_request", requestMap);
        params.put("operationID", ConstantEnum.HIS_CIRCULATION_10044.getKey());
        System.out.println(JSON.toJSONString(params));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, params);

        if (jsonObject.isEmpty()) {
            //return ResultGenerator.genFailedResult("门诊领药数据检查失败");
        }
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {

            } else if (resInt == 1) {
                Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                });
                Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");
                Map<String, Object> yllb = (Map<String, Object>) response.get("yllb");
                yllbList = (List<Map<String, Object>>) yllb.get("yllb_list");
            }
        }


        //param.put("operationID",ConstantEnum.HIS_CIRCULATION_10044.getKey());
        //JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
        //JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, param);
        /*Integer resInt = Integer.valueOf((String)jsonObject.get("Error_Id"));
        if (resInt < 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultGenerator.genFailedResult("HIS接口调用失败");
        }else{
            return ResultGenerator.genOkResult(jsonObject.get("data"));
        }*/
        return ResultGenerator.genOkResult(yllbList);
    }

    /**
     * 获取出院诊断
     *
     * @param inpatNum
     * @return
     */
    public Result queryDischargeDiagnosis(String inpatNum) {
        return ResultGenerator.genOkResult(circulationLogMapper.queryDischargeDiagnosisByInpatNum(inpatNum));
    }

    /**
     * 根据住院号获取备注信息
     *
     * @param inpatNum
     * @return
     */
    public Result queryPatientFinishutHospByInpatNum(String inpatNum) {
        //增加待出院入院日志
        CirculationLogEntity outCirculationLogEntity = circulationLogMapper.selectNewLogOutHospByInpatNum(inpatNum);
        if (outCirculationLogEntity == null) {
            return ResultGenerator.genFailedResult("此病人已出院流转记录！");
        }
        Map map = JSONObject.parseObject(outCirculationLogEntity.getRemark(), Map.class);
        map.put("outDatetime", DateUtil.dateToString(new Date(outCirculationLogEntity.getOutDatetime().getTime()), "yyyy-MM-dd HH:mm"));
        return ResultGenerator.genOkResult(map);
    }

    /**
     * 获取医疗类别
     *
     * @return
     */
    public Result dischargeMode() {
        Map<String, Object> param = new HashMap<>();
        param.put("operationID", ConstantEnum.HIS_CIRCULATION_10042.getKey());
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
        if (resInt < 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultGenerator.genFailedResult("HIS接口调用失败");
        } else {
            return ResultGenerator.genOkResult(jsonObject.get("data"));
        }
    }

    @Override
    public Result queryDeptByWardDeptId(String type, String contentId) {
        List<Map<String, String>> list;
        if (StringUtils.isNotEmpty(type) && type.equals("dept")) {
            list = circulationLogMapper.queryWardDeptByDeptId(contentId,null,null);
        } else {
            list = circulationLogMapper.queryDeptByWardDeptId(contentId,null,null);
        }
        return ResultGenerator.genOkResult(list);
    }

    public Result queryDeptByWardDeptId2(String type, String contentId,String id,Integer page,Integer pageSize,String keyWords){
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = new CopyOnWriteArrayList<>();
        if (StringUtils.isNotEmpty(type) && type.equals("dept")) {
            list = circulationLogMapper.queryWardDeptByDeptId(contentId,id,keyWords);
        } else {
            list = circulationLogMapper.queryDeptByWardDeptId(contentId,id,keyWords);
        }
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result patientOperation(String inpatNum, String operation, String remark, String circulationlLogId) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        Map<String, String> patientOperationMap = new HashMap<String, String>();
        List<String> nextModeTypes = new ArrayList<>();
        String modelName = "";
        String errorMsg = "此病人无待处理信息";
        if (OperationTypeEnum.ZERO.getKey().equals(operation)) {
            nextModeTypes.add(CirculationModelEnum.WAIT_OUT_WARD.getCode());
            nextModeTypes.add(CirculationModelEnum.FINISH_OUT_WARD.getCode());
            nextModeTypes.add(CirculationModelEnum.WAIT_IN_OPERATION.getCode());
            modelName = "out_ward";
            PatientInHospitalEntity patientInHospitalInfo = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
            CirculationLogEntity circulationLogEntity = circulationLogMapper.getPatientInfo(inpatNum, CirculationModelEnum.WAIT_OUT_WARD.getCode(), "0", circulationlLogId);
            //获取医嘱id，获取手术时间
            if (circulationLogEntity != null) {
                String operationTime = circulationLogMapper.queryOperationTime(circulationLogEntity.getInpatorderdataId());
                Map<String, String> operationInfo = circulationLogMapper.queryPatientOperationByInpatorderdataId(circulationLogEntity.getInpatorderdataId());
                //his对接
                Map<String, Object> param = new HashMap<>();
                //病人编码 住院号
                param.put("p_patient_id", patientInHospitalInfo.getMedicalNum());
                //就诊次数 住院号-后的值
                param.put("p_visit_id", patientInHospitalInfo.getInpatTimes());
                //排序字段及方向
                param.put("p_sort", "");
                //当前页-默认第一页
                param.put("p_curPage", "1");
                //每页行数-默认每页10行
                param.put("p_pageSize", "10");
                //手术操作码
                param.put("operationID", ConstantEnum.HIS_CIRCULATION_10046.getKey());
                System.out.println(JSON.toJSONString(param));

                JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
                if (jsonObject.isEmpty()) {
                    return ResultGenerator.genFailedResult("手术获取数据失败");
                }
                Integer resInt = Integer.valueOf((String) jsonObject.get("p_totalRecords"));
                if (resInt < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    //return ResultGenerator.genFailedResult("HIS接口调用失败");
                    return ResultGenerator.genFailedResult("手术获取数据失败");
                }
                if (jsonObject.getString("data") != null) {
                    List<Map> list = JSONArray.parseArray(jsonObject.getString("data"), Map.class);
                    if (list != null && list.size() > 0) {
                        for (Map oMap : list) {
                            if (CommonUtils.isNotEmpty((String) oMap.get("OPERATING_ROOM_NO")) && CommonUtils.isNotEmpty((String) oMap.get("ARRANGE_DATE_TIME"))) {
                                if ((oMap.get("OPERATION")).equals(operationInfo.get("operationName")) && operationTime.equals(oMap.get("SCHEDULED_DATE_TIME"))) {
                                    patientOperationMap = oMap;
                                }
                            }
                        }
                    }
                }
            }

        } else if (OperationTypeEnum.ONE.getKey().equals(operation)) {
            nextModeTypes.add(CirculationModelEnum.WAIT_IN_OPERATION.getCode());
            nextModeTypes.add(CirculationModelEnum.FINISH_IN_OPERATION.getCode());
            nextModeTypes.add(CirculationModelEnum.WAIT_OUT_OPERATION.getCode());
            modelName = "in_operation";
        } else if (OperationTypeEnum.TWO.getKey().equals(operation)) {
            errorMsg = "请先进行病人转入确认";
            nextModeTypes.add(CirculationModelEnum.WAIT_OUT_OPERATION.getCode());
            nextModeTypes.add(CirculationModelEnum.FINISH_OUT_OPERATION.getCode());
            nextModeTypes.add(CirculationModelEnum.WAIT_IN_RESUSCITATION.getCode());
        } else if (OperationTypeEnum.THREE.getKey().equals(operation)) {
            nextModeTypes.add(CirculationModelEnum.WAIT_IN_RESUSCITATION.getCode());
            nextModeTypes.add(CirculationModelEnum.FINISH_IN_RESUSCITATION.getCode());
            nextModeTypes.add(CirculationModelEnum.WAIT_OUT_RESUSCITATION.getCode());
        } else if (OperationTypeEnum.FOUR.getKey().equals(operation)) {

            errorMsg = "请先进行病人转入确认";
            nextModeTypes.add(CirculationModelEnum.WAIT_OUT_RESUSCITATION.getCode());
            nextModeTypes.add(CirculationModelEnum.FINISH_OUT_RESUSCITATION.getCode());
            nextModeTypes.add(CirculationModelEnum.WAIT_IN_OPERATION.getCode());
        } else if (OperationTypeEnum.FIVE.getKey().equals(operation)) {
            errorMsg = "请先进行病人转入确认";
            nextModeTypes.add(CirculationModelEnum.WAIT_OUT_OPERATION.getCode());
            nextModeTypes.add(CirculationModelEnum.FINISH_OUT_OPERATION.getCode());
            nextModeTypes.add(CirculationModelEnum.WAIT_IN_WARD.getCode());
        } else if (OperationTypeEnum.SIX.getKey().equals(operation)) {
            nextModeTypes.add(CirculationModelEnum.WAIT_IN_WARD.getCode());
            nextModeTypes.add(CirculationModelEnum.FINISH_IN_WARD.getCode());
            modelName = "in_ward";
        } else if (OperationTypeEnum.SEVEN.getKey().equals(operation)) {
            nextModeTypes.add(CirculationModelEnum.WAIT_OUT_RESUSCITATION.getCode());
            nextModeTypes.add(CirculationModelEnum.FINISH_OUT_RESUSCITATION.getCode());
            nextModeTypes.add(CirculationModelEnum.WAIT_IN_WARD.getCode());
        }

        if (StringUtils.isNotBlank(modelName)) {
            //验证是否必填资料是否全部完成
            List<String> isAllFinish = circulationTemplateMapper.checkIsFinish(inpatNum, modelName);
            if (null != isAllFinish && isAllFinish.size() > 0) {
                errorMsg = "请优先完成任务" + isAllFinish.stream().collect(Collectors.joining(",")) + "";
                return ResultGenerator.genFailedResult(JSONArray.toJSONString(isAllFinish));
            }
        }

        //获取
        String waitCirculationLogId = null;
        String finishCirculationLogId = null;
        for (int i = 1; i < nextModeTypes.size(); i++) {
            String nextModeType = nextModeTypes.get(i - 1);
            String nextNextModeType = nextModeTypes.get(i);
            String status = "0";
            if (nextModeType.startsWith("finish")) {
                status = "1";
            }
            String currentCirculationLogId = null;
            if (i == 1) {
                //waitCirculationLogId=circulationLogEntity.getCirculationLogId();
                currentCirculationLogId = circulationlLogId;
            } else if (i == 2) {
                currentCirculationLogId = finishCirculationLogId;
            }
            CirculationLogEntity circulationLogEntity = circulationLogMapper.getPatientInfo(inpatNum, nextModeType, status, currentCirculationLogId);
            if (null == circulationLogEntity) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultGenerator.genFailedResult(errorMsg);
            }
            if (i == 1) {
                waitCirculationLogId = circulationLogEntity.getCirculationLogId();
            }
            //circulationLogMapper.updateStatusByInpatNum(inpatNum, nextModeType);
            circulationLogMapper.updateStatusByInpatNum(circulationLogEntity.getCirculationLogId(),userId);
            CirculationLogEntity next = new CirculationLogEntity();
            BeanUtils.copyProperties(circulationLogEntity, next);
            next.setCirculationLogId(UUIDUtil.randomString());
            if (i == 1) {
                finishCirculationLogId = next.getCirculationLogId();
            }
            next.setSerialNo(circulationLogEntity.getSerialNo() + 1);
            next.setCirculationModelType(nextNextModeType);
            if (nextNextModeType.startsWith("finish")) {
                next.setStatus(1);
            } else {
                next.setStatus(0);
            }
            next.initAdd();
            /*if (StringUtils.isNotBlank(remark)) {
                next.setRemark(remark);
            }*/
            if (StringUtils.isNotBlank(remark)) {
                if (patientOperationMap.isEmpty()) {
                    if (StringUtils.isNotBlank(next.getRemark())) {
                        patientOperationMap = JSONObject.parseObject(next.getRemark(), Map.class);
                        patientOperationMap.remove("remark");
                    }
                    patientOperationMap.put("remark", remark);
                    String resultRemark = JSON.toJSONString(patientOperationMap);
                    next.setRemark(resultRemark);
                    patientOperationMap = new HashMap<String, String>();
                } else {
                    patientOperationMap.put("remark", remark);
                    String resultRemark = JSON.toJSONString(patientOperationMap);
                    next.setRemark(resultRemark);
                    patientOperationMap = new HashMap<String, String>();
                }
            } else {
                if (patientOperationMap.isEmpty()) {
                    if (StringUtils.isNotBlank(next.getRemark())) {
                        patientOperationMap = JSONObject.parseObject(next.getRemark(), Map.class);
                        patientOperationMap.remove("remark");
                        String resultRemark = JSON.toJSONString(patientOperationMap);
                        next.setRemark(resultRemark);
                        patientOperationMap = new HashMap<String, String>();
                    }
                }
            }
            next.setOperator(userId);
            if (OperationTypeEnum.ZERO.getKey().equals(operation)) {
                if (i == 1) {
                    this.setValueOperationRoomIn(next);
                    next.setOutDatetime(new Timestamp(next.getCreateTime().getTime()));
                    next.setModifyTime(new Timestamp(next.getCreateTime().getTime()));
                }
                if (i == 2) {
                    next.setOutDatetime(null);
                    next.setOutBedLabel(null);
                }
            }else if(OperationTypeEnum.ONE.getKey().equals(operation)){
                if (i == 1) {
                    next.setInDatetime(new Timestamp(next.getCreateTime().getTime()));
                    next.setModifyTime(new Timestamp(next.getCreateTime().getTime()));
                }
                if (i == 2) {
                    next.setOutDatetime(null);
                    next.setOutBedNo(null);
                    next.setOutBedLabel(null);
                    next.setOutDoctorPersonId(null);
                    next.setOutNurseId(null);
                    next.setInDatetime(null);
                    next.setInWardDeptId(null);
                    next.setInDeptId(null);
                    next.setInBedNo(null);
                    next.setInBedLabel(null);
                    next.setInDoctorPersonId(null);
                    next.setInNurseId(null);
                    this.setValueOperationRoomOut(next);
                }
            }else if(OperationTypeEnum.TWO.getKey().equals(operation)){
                if (i == 1) {
                    next.setOutDatetime(new Timestamp(next.getCreateTime().getTime()));
                    next.setModifyTime(new Timestamp(next.getCreateTime().getTime()));
                    this.setValueResuscitationRoomIn(next);
                }
                if (i == 2){
                    next.setOutDatetime(null);
                }
            }else if(OperationTypeEnum.THREE.getKey().equals(operation)){
                if (i == 1) {
                    next.setInDatetime(new Timestamp(next.getCreateTime().getTime()));
                    next.setModifyTime(new Timestamp(next.getCreateTime().getTime()));
                }
                if (i == 2) {
                    next.setOutDatetime(null);
                    next.setOutBedNo(null);
                    next.setOutBedLabel(null);
                    next.setOutDoctorPersonId(null);
                    next.setOutNurseId(null);
                    next.setInDatetime(null);
                    next.setInWardDeptId(null);
                    next.setInDeptId(null);
                    next.setInBedNo(null);
                    next.setInBedLabel(null);
                    next.setInDoctorPersonId(null);
                    next.setInNurseId(null);
                    this.setValueResuscitationRoomOut(next);
                }
            }else if (OperationTypeEnum.FOUR.getKey().equals(operation)) {
                if (i == 1) {
                    next.setInDatetime(null);
                    this.setValueOperationRoomIn(next);
                    next.setOutDatetime(new Timestamp(next.getCreateTime().getTime()));
                    next.setModifyTime(new Timestamp(next.getCreateTime().getTime()));
                }
                if (i == 2) {
                    next.setOutDatetime(null);
                }
            }else if (OperationTypeEnum.FIVE.getKey().equals(operation)) {
                if (i == 1) {
                    next.setOutDatetime(new Timestamp(next.getCreateTime().getTime()));
                    next.setModifyTime(new Timestamp(next.getCreateTime().getTime()));
                    this.setValueWardIn(inpatNum,next);
                }
                if (i == 2){
                    next.setOutDatetime(null);
                }
            }else if (OperationTypeEnum.SIX.getKey().equals(operation)) {
                if (i == 1) {
                    next.setInDatetime(new Timestamp(next.getCreateTime().getTime()));
                    next.setModifyTime(new Timestamp(next.getCreateTime().getTime()));
                }
            }else if (OperationTypeEnum.SEVEN.getKey().equals(operation)) {
                if (i == 1) {
                    next.setInDatetime(null);
                    this.setValueWardIn(inpatNum,next);
                    next.setOutDatetime(new Timestamp(next.getCreateTime().getTime()));
                    next.setModifyTime(new Timestamp(next.getCreateTime().getTime()));
                }
                if (i == 2) {
                    next.setOutDatetime(null);
                }

            }
            circulationLogMapper.insert(next);
        }

        //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
        List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(waitCirculationLogId);
        //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
        if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
            commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, finishCirculationLogId);
        }

        return ResultGenerator.genOkResult();
    }

    public void setValueOperationRoomIn(CirculationLogEntity next){
        if(StringUtils.isNotBlank(next.getRemark())){
            Map<String, String> patientOperationMap = JSONObject.parseObject(next.getRemark(), Map.class);
            //获取手术室 编号
            String operatingRoom = patientOperationMap.get("OPERATING_ROOM");
            //根据手术室编号获取科室id
            Map<String, String> deptInfo = circulationLogMapper.queryDeptByCode(operatingRoom);
            if(deptInfo!=null){
                next.setInDeptId(deptInfo.get("deptId"));
                next.setInWardDeptId(this.getOperationRoomWardDeptId(deptInfo.get("deptArea")));
            }
        }
    }

    public void setValueOperationRoomOut(CirculationLogEntity next){
        if(StringUtils.isNotBlank(next.getRemark())) {
            Map<String, String> patientOperationMap = JSONObject.parseObject(next.getRemark(), Map.class);
            //获取手术室 编号
            String operatingRoom = patientOperationMap.get("OPERATING_ROOM");
            //根据手术室编号获取科室id
            Map<String, String> deptInfo = circulationLogMapper.queryDeptByCode(operatingRoom);
            if (deptInfo != null) {
                next.setOutDeptId(deptInfo.get("deptId"));
                next.setOutWardDeptId(this.getOperationRoomWardDeptId(deptInfo.get("deptArea")));
            }
        }
    }

    public void setValueResuscitationRoomIn(CirculationLogEntity next){
        if(StringUtils.isNotBlank(next.getRemark())) {
            Map<String, String> patientOperationMap = JSONObject.parseObject(next.getRemark(), Map.class);
            //获取手术室 编号
            String operatingRoom = patientOperationMap.get("OPERATING_ROOM");
            //根据手术室编号获取科室id
            Map<String, String> deptInfo = circulationLogMapper.queryDeptByCode(operatingRoom);
            if (deptInfo != null) {
                next.setInDeptId(deptInfo.get("deptId"));
                next.setInWardDeptId(this.getResuscitationRoomWardDeptId(deptInfo.get("deptArea")));
            }
        }
    }

    public void setValueResuscitationRoomOut(CirculationLogEntity next){
        if(StringUtils.isNotBlank(next.getRemark())) {
            Map<String, String> patientOperationMap = JSONObject.parseObject(next.getRemark(), Map.class);
            //获取手术室 编号
            String operatingRoom = patientOperationMap.get("OPERATING_ROOM");
            //根据手术室编号获取科室id
            Map<String, String> deptInfo = circulationLogMapper.queryDeptByCode(operatingRoom);
            if (deptInfo != null) {
                next.setOutDeptId(deptInfo.get("deptId"));
                next.setOutWardDeptId(this.getResuscitationRoomWardDeptId(deptInfo.get("deptArea")));
            }
        }
    }

    public void setValueWardIn(String inpatNum,CirculationLogEntity next){
        //获取手术室 编号
        Map<String, String> patientInfo = circulationLogMapper.queryDeptByInpatNum(inpatNum);
        String bedLabel = circulationLogMapper.queryBedLabel(patientInfo.get("wardDeptId"),patientInfo.get("bedNO"));
        if(patientInfo!=null){
            next.setInDeptId(patientInfo.get("deptId"));
            next.setInWardDeptId(patientInfo.get("wardDeptId"));
            next.setInBedNo(patientInfo.get("bedNO"));
            next.setInBedLabel(bedLabel);
            next.setInDoctorPersonId(patientInfo.get("doctorId"));
            next.setInNurseId(patientInfo.get("nurseId"));
        }
    }

    public String getOperationRoomWardDeptId(String type){
        if("01".equals(type)){
            return "F0F3BC5868CE47F583CB08EC6E46B1D6";
        }else if("02".equals(type)){
            return "5D04523554944A30A5FB81F57E985763";
        }
        return null;
    }

    public String getResuscitationRoomWardDeptId(String type){
        if("01".equals(type)){
            return "95037CF5C9465245E053ED5B14ACFD88";
        }else if("02".equals(type)){
            return "95037CF5C9475245E053ED5B14ACFD88";
        }
        return null;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result patientTransferOut(String inpatNum, String transport, String wardDeptId,String circulationLogId,String transferOutDateTime,
                                     String stopDateTime,String babyStopDateTime) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<String> isAllFinish = circulationTemplateMapper.checkIsFinish(inpatNum, "out_dept");
        if (null != isAllFinish && isAllFinish.size() > 0) {
            return ResultGenerator.genFailedResult(StringUtils.join(isAllFinish.toArray()) + "未完成，无法保存");
        }

        List<Map<String, String>> rotatingList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.INCOMPLETE.getValue(), CirculationTypeEnum.TRANSFERRED_DEPT.getCode(), CirculationModelEnum.WAIT_OUT_DEPT.getCode(), null, circulationLogId);//获取待转出日志
        try {
            if (rotatingList == null || rotatingList.size() <= 0)
                return ResultGenerator.genFailedResult("此病人无待转出转科记录");

            PatientInHospitalEntity patientInHospitalInfo = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);

            Map<String, String> patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, rotatingList.get(0).get("CIRCULATION_LOG_ID"));

            //待转入日志id
            String logId = UUIDUtil.randomString();

            String lastStopDateTime="";
            if(StringUtils.isNotBlank(stopDateTime)){
                lastStopDateTime=stopDateTime+":00";
            }else if(StringUtils.isNotBlank(babyStopDateTime)){
                lastStopDateTime=babyStopDateTime+":00";
            }
            if(StringUtils.isNotBlank(lastStopDateTime)){
                lastStopDateTime=lastStopDateTime.replace("+"," ");
            }
            if(StringUtils.isNotBlank(transferOutDateTime)){
                transferOutDateTime=transferOutDateTime.replace("+"," ");
            }

            //调用转科his接口
            Map<String, Object> param = new HashMap<>();
            //病人编码 住院号
            param.put("p_patient_id", patientInHospitalInfo.getMedicalNum());
            //就诊次数 住院号-后的值
            param.put("p_visit_id", patientInHospitalInfo.getInpatTimes());
            //床号
            param.put("p_bed_no", rotatingList.get(0).get("OUT_BED_NO"));
            //原病区代码
            param.put("p_ward_code_old", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("OUT_WARD_DEPT_ID")));
            //原科室代码
            param.put("p_dept_code_old", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("OUT_DEPT_ID")));
            //转入科室
            param.put("p_dept_code_new", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("IN_DEPT_ID")));
            //转入病区代码
            //param.put("p_ward_code_new", patientInHospitalMapper.queryDeptCodeByDeptId(patient.get("inWardId")));
            param.put("p_ward_code_new", patientInHospitalMapper.queryDeptCodeByDeptId(wardDeptId));
            //转出时间
            //param.put("p_discharge_date_time", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            param.put("p_discharge_date_time", transferOutDateTime + ":00");
            //转入科室责任医生
            param.put("p_doctor", patientInHospitalMapper.queryUserIdByPersonId(rotatingList.get(0).get("OUT_DOCTOR_PERSON_ID")));
            param.put("p_stop_date_time", lastStopDateTime);
            //转出科室操作码
            param.put("operationID", ConstantEnum.HIS_CIRCULATION_10035.getKey());
            System.out.println(JSON.toJSONString(param));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
            if (jsonObject.isEmpty()) {
                return ResultGenerator.genFailedResult("患者转科转出失败");
            }
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //return ResultGenerator.genFailedResult("HIS接口调用失败");
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            }else {
                //插入中间表
                //hzif.tmp_circulation_log
                //circulationLogMapper.insertTmpCirculationLog(null,logId);
                String pPrimaryId = jsonObject.getString("p_primary_id");
                if(StringUtils.isNotBlank(pPrimaryId)){
                    String[] pIds = pPrimaryId.split("\\$");
                    for(String pId:pIds){
                        if(StringUtils.isNotBlank(pId)){
                            if(!(pId.split("-")[1].contains(patientInHospitalInfo.getMedicalNum()+"B"))){
                                //插入中间表
                                //hzif.tmp_circulation_log
                                circulationLogMapper.insertTmpCirculationLog(pId,logId);
                            }
                        }
                    }
                }
            }

            for (Map<String, String> rotating : rotatingList) {

                String turnBed = rotating.get("IN_BED_NO");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //circulationLogMapper.updateLogStatusById(rotating.get("CIRCULATION_LOG_ID"), null, sdf.format(new Date()), StateEnum.COMPLETED.getValue(),userId);//更新待转出状态
                circulationLogMapper.updateLogStatusById2(rotating.get("CIRCULATION_LOG_ID"), null, transferOutDateTime+":00", StateEnum.COMPLETED.getValue(),userId,wardDeptId,rotating.get("IN_DEPT_ID"));//更新待转出状态

                //Map<String, String> patient = patientService.getPatientInfoNurse(inpatNum, null, null, null);
                CirculationLogEntity entity2 = new CirculationLogEntity();//已转出新增
                entity2.setCirculationLogId(UUIDUtil.randomString());
                entity2.initAdd();
                entity2.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));//已完成
                entity2.setCirculationModelType(CirculationModelEnum.FINISH_OUT_DEPT.getCode());
                entity2.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
                entity2.setInpatNum(inpatNum);
                entity2.setOutDatetime(new Timestamp(DateUtil.stringToDate(transferOutDateTime+":00").getTime()));
                entity2.setInDeptId(rotating.get("IN_DEPT_ID"));
                entity2.setOutDeptId(rotating.get("OUT_DEPT_ID"));
                entity2.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
                entity2.setSourceType("SELF");
                //entity2.setSerialNo(1);
                entity2.setSerialNo(rotating.get("serialNo") == null ? 1 : (Integer.parseInt(rotating.get("serialNo"))) + 1);
                entity2.setCancelFlag(0);
                //entity2.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity2.setRemark(transport);
                entity2.setPatTypeId(rotating.get("PAT_TYPE_ID"));
                entity2.setHealthNum(rotating.get("HEALTH_NUM"));
                entity2.setOutDoctorPersonId(rotating.get("OUT_DOCTOR_PERSON_ID"));
                entity2.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                entity2.setInBedNo(rotating.get("IN_BED_NO"));
                entity2.setInBedLabel(rotating.get("IN_BED_LABEL"));
                entity2.setOutBedNo(rotating.get("OUT_BED_NO"));
                entity2.setOutBedLabel(rotating.get("OUT_BED_LABEL"));
                //entity2.setInWardDeptId(patient.get("inWardId"));
                //entity2.setOutWardDeptId(patient.get("outWardId"));
                entity2.setInWardDeptId(wardDeptId);
                entity2.setOutWardDeptId(rotating.get("OUT_WARD_DEPT_ID"));

                entity2.setInNurseId(rotating.get("IN_NURSE_ID"));
                entity2.setOutNurseId(rotating.get("OUT_NURSE_ID"));
                entity2.setOperator(userId);
                circulationLogMapper.insert(entity2);

                CirculationLogEntity entity3 = new CirculationLogEntity();//待转入新增
                entity3.initAdd();
                entity3.setStatus(Integer.parseInt(StateEnum.INCOMPLETE.getValue()));
                entity3.setCirculationLogId(logId);
                entity3.setCirculationModelType(CirculationModelEnum.WAIT_IN_DEPT.getCode());
                entity3.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
                entity3.setInpatNum(inpatNum);
                entity3.setOutDatetime(new Timestamp(new Date().getTime()));
                entity3.setInDeptId(rotating.get("IN_DEPT_ID"));
                entity3.setOutDeptId(rotating.get("OUT_DEPT_ID"));
                entity3.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
                entity3.setSourceType("SELF");
                //entity3.setSerialNo(1);
                entity3.setSerialNo(entity2.getSerialNo() + 1);
                entity3.setCancelFlag(0);
                entity3.setInWardDeptId(patient.get("inWardId"));
                entity3.setRemark(transport);
                entity3.setPatTypeId(rotating.get("PAT_TYPE_ID"));
                entity3.setHealthNum(rotating.get("HEALTH_NUM"));
                entity3.setOutDoctorPersonId(rotating.get("OUT_DOCTOR_PERSON_ID"));
                entity3.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                entity3.setInBedNo(rotating.get("IN_BED_NO"));
                entity3.setOutBedNo(rotating.get("OUT_BED_NO"));
                entity2.setInBedLabel(rotating.get("IN_BED_LABEL"));
                entity3.setOutBedLabel(rotating.get("OUT_BED_LABEL"));
                //entity3.setInWardDeptId(patient.get("inWardId"));
                //entity3.setOutWardDeptId(patient.get("outWardId"));
                entity3.setInWardDeptId(wardDeptId);
                entity3.setOutWardDeptId(rotating.get("OUT_WARD_DEPT_ID"));
                entity3.setInNurseId(rotating.get("IN_NURSE_ID"));
                entity3.setOutNurseId(rotating.get("OUT_NURSE_ID"));
                entity3.setOperator(userId);
                entity3.setOutDatetime(new Timestamp(DateUtil.stringToDate(transferOutDateTime+":00").getTime()));
                circulationLogMapper.insert(entity3);

                //更新病人信息表
                circulationLogMapper.updatePatientOut(inpatNum, null, null, null);

                //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
                List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(rotating.get("CIRCULATION_LOG_ID"));
                //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
                if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                    commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, entity2.getCirculationLogId());
                }

                //更新床号 原床状态为0
                circulationLogMapper.updateBedNoStatus(rotatingList.get(0).get("OUT_BED_NO"), rotatingList.get(0).get("OUT_WARD_DEPT_ID"), "0");

                /*Query query = new Query();
                query.addCriteria(Criteria.where("inpatNum").is(inpatNum));
                doctorMongoTemplate.remove(query,PatientInHospInfo.class);*/
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转科转出失败" + e.getMessage());
            return ResultGenerator.genFailedResult("转科转出失败");
        }

        //等待请求his todo
        return ResultGenerator.genOkResult();
    }

    public Result patientTransferOutPc(String inpatNum,String circulationLogId,
                                String transferOutWardDeptId,String transferOutDeptId,
                                String transferInWardDeptId,String transferInDeptId,
                                String transferOutDateTime,String stopDateTime,String babyStopDateTime){
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            List<Map<String, String>> rotatingList = new CopyOnWriteArrayList<>();
            Map<String, String> patient  = new CopyOnWriteMap<>();
            PatientInHospitalEntity patientInHospitalInfo = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
            if(StringUtils.isNotBlank(circulationLogId)){
                rotatingList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.INCOMPLETE.getValue(), CirculationTypeEnum.TRANSFERRED_DEPT.getCode(), CirculationModelEnum.WAIT_OUT_DEPT.getCode(), null, circulationLogId);//获取待转出日志
                if (CollectionUtils.isEmpty(rotatingList)) {
                    return ResultGenerator.genFailedResult("此病人无待转出转科记录");
                }
                patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, rotatingList.get(0).get("CIRCULATION_LOG_ID"));
            }else{
                patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, null);
            }

            String lastStopDateTime="";
            if(StringUtils.isNotBlank(stopDateTime)){
                lastStopDateTime=stopDateTime+":00";
            }else if(StringUtils.isNotBlank(babyStopDateTime)){
                lastStopDateTime=babyStopDateTime+":00";
            }
            if(StringUtils.isNotBlank(lastStopDateTime)){
                lastStopDateTime=lastStopDateTime.replace("+"," ");
            }
            if(StringUtils.isNotBlank(transferOutDateTime)){
                transferOutDateTime=transferOutDateTime.replace("+"," ");
            }
            //待转入日志id
            String logId = UUIDUtil.randomString();
            String nurseId = null;
            //获取手术室 编号
            Map<String, String> patientInfo = circulationLogMapper.queryDeptByInpatNum(inpatNum);
            if(patientInfo!=null){
                nurseId = patientInfo.get("nurseId");
            }
            //调用转科his接口
            Map<String, Object> param = new HashMap<>();
            //病人编码 住院号
            param.put("p_patient_id", patientInHospitalInfo.getMedicalNum());
            //就诊次数 住院号-后的值
            param.put("p_visit_id", patientInHospitalInfo.getInpatTimes());
            //床号
            param.put("p_bed_no", patientInHospitalInfo.getBedNo());
            //原病区代码
            param.put("p_ward_code_old", patientInHospitalMapper.queryDeptCodeByDeptId(transferOutWardDeptId));
            //原科室代码
            param.put("p_dept_code_old", patientInHospitalMapper.queryDeptCodeByDeptId(transferOutDeptId));
            //转入科室
            param.put("p_dept_code_new", patientInHospitalMapper.queryDeptCodeByDeptId(transferInDeptId));
            //转入病区代码
            param.put("p_ward_code_new", patientInHospitalMapper.queryDeptCodeByDeptId(transferInWardDeptId));
            //转出时间
            param.put("p_discharge_date_time", transferOutDateTime + ":00");
            //转入科室责任医生
            param.put("p_doctor", patientInHospitalMapper.queryUserIdByPersonId(patientInHospitalInfo.getResponsibleDoctorPersonId()));
            param.put("p_stop_date_time", lastStopDateTime);
            //转出科室操作码
            param.put("operationID", ConstantEnum.HIS_CIRCULATION_10035.getKey());
            System.out.println(JSON.toJSONString(param));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
            if (jsonObject.isEmpty()) {
                return ResultGenerator.genFailedResult("患者转科转出失败");
            }
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //return ResultGenerator.genFailedResult("HIS接口调用失败");
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            }else {
                //p_primary_id -> H2127-764537-1-20210125201600-E$
                String pPrimaryId = jsonObject.getString("p_primary_id");
                if(StringUtils.isNotBlank(pPrimaryId)){
                    String[] pIds = pPrimaryId.split("\\$");
                    for(String pId:pIds){
                        if(StringUtils.isNotBlank(pId)){
                            if(!(pId.split("-")[1].contains(patientInHospitalInfo.getMedicalNum()+"B"))){
                                //插入中间表
                                //hzif.tmp_circulation_log
                                circulationLogMapper.insertTmpCirculationLog(pId,logId);
                            }
                        }
                    }
                }
            }
            Map<String, String> rotating = new CopyOnWriteMap<>();
            if (!CollectionUtils.isEmpty(rotatingList)) {
                rotating = rotatingList.get(0);
                String turnBed = rotating.get("IN_BED_NO");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                circulationLogMapper.updateLogStatusById2(rotating.get("CIRCULATION_LOG_ID"), null, transferOutDateTime + ":00", StateEnum.COMPLETED.getValue(),
                                                         userId,transferInWardDeptId,transferInDeptId);//更新待转出状态
            }

            CirculationLogEntity entity2 = new CirculationLogEntity();//已转出新增
            entity2.initAdd();
            entity2.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));//已完成
            entity2.setCirculationLogId(UUIDUtil.randomString());
            entity2.setCirculationModelType(CirculationModelEnum.FINISH_OUT_DEPT.getCode());
            entity2.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
            entity2.setInpatNum(inpatNum);
            entity2.setOutDatetime(new Timestamp(DateUtil.stringToDate(transferOutDateTime + ":00").getTime()));
            entity2.setInDeptId(transferInDeptId);
            entity2.setOutDeptId(transferOutDeptId);
            if(rotating!=null){
                entity2.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
            }
            entity2.setSourceType("SELF");
            //entity2.setSerialNo(1);
            entity2.setSerialNo((rotating == null || rotating.get("serialNo") == null) ? 1 : (Integer.parseInt(rotating.get("serialNo"))) + 1);
            entity2.setCancelFlag(0);
            entity2.setInWardDeptId(transferInWardDeptId);
            entity2.setRemark(null);
            entity2.setPatTypeId(patientInHospitalInfo.getPatTypeId());
            entity2.setHealthNum(patientInHospitalInfo.getHealthNum());
            entity2.setOutDoctorPersonId(patientInHospitalInfo.getResponsibleDoctorPersonId());
            entity2.setInDoctorPersonId(null);
            entity2.setInBedNo(null);
            entity2.setInBedLabel(null);
            entity2.setOutBedNo((rotating == null || rotating.get("OUT_BED_NO") ==null)?patientInHospitalInfo.getBedNo():rotating.get("OUT_BED_NO"));
            String outBedLabel = circulationLogMapper.queryBedLabel(transferOutWardDeptId,entity2.getOutBedNo());
            entity2.setOutBedLabel((rotating == null || rotating.get("OUT_BED_LABEL") ==null)?outBedLabel:rotating.get("OUT_BED_LABEL"));
            entity2.setInWardDeptId(transferInWardDeptId);
            entity2.setOutWardDeptId(transferOutWardDeptId);
            entity2.setInNurseId(null);
            entity2.setOutNurseId(nurseId);
            entity2.setOperator(userId);
            circulationLogMapper.insert(entity2);

            CirculationLogEntity entity3 = new CirculationLogEntity();//待转入新增
            entity3.initAdd();
            entity3.setStatus(Integer.parseInt(StateEnum.INCOMPLETE.getValue()));
            entity3.setCirculationLogId(logId);
            entity3.setCirculationModelType(CirculationModelEnum.WAIT_IN_DEPT.getCode());
            entity3.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
            entity3.setInpatNum(inpatNum);
            entity3.setOutDatetime(new Timestamp(new Date().getTime()));
            entity3.setInDeptId(transferInDeptId);
            entity3.setOutDeptId(transferOutDeptId);
            if(rotating!=null){
                entity3.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
            }
            entity3.setSourceType("SELF");
            //entity3.setSerialNo(1);
            entity3.setSerialNo(entity2.getSerialNo() + 1);
            entity3.setCancelFlag(0);
            entity3.setInWardDeptId(patient.get("inWardId"));
            entity3.setRemark(null);
            entity3.setPatTypeId(patientInHospitalInfo.getPatTypeId());
            entity3.setHealthNum(patientInHospitalInfo.getHealthNum());
            entity3.setOutDoctorPersonId(patientInHospitalInfo.getResponsibleDoctorPersonId());
            entity3.setInDoctorPersonId(null);
            entity3.setInBedNo(null);
            entity3.setInBedLabel(null);
            entity3.setOutBedNo((rotating == null || rotating.get("OUT_BED_NO") ==null)?patientInHospitalInfo.getBedNo():rotating.get("OUT_BED_NO"));
            entity3.setOutBedLabel((rotating == null || rotating.get("OUT_BED_LABEL") ==null)?outBedLabel:rotating.get("OUT_BED_LABEL"));
            entity3.setInWardDeptId(transferInWardDeptId);
            entity3.setOutWardDeptId(transferOutWardDeptId);
            entity3.setInNurseId(null);
            entity3.setOutNurseId(nurseId);
            entity3.setOperator(userId);
            entity3.setOutDatetime(new Timestamp(DateUtil.stringToDate(transferOutDateTime + ":00").getTime()));
            circulationLogMapper.insert(entity3);

            //更新病人信息表
            circulationLogMapper.updatePatientOut(inpatNum, null, null, null);

            //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
            List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(circulationLogId);
            //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
            if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, entity2.getCirculationLogId());
            }

            //更新床号 原床状态为0

            circulationLogMapper.updateBedNoStatus(patientInHospitalInfo.getBedNo(), transferOutWardDeptId, "0");

            //等待请求his
            return ResultGenerator.genOkResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result patientTransferIn(String inpatNum, String transport, String bedNo, String doctorPersonId, String nurseId,String circulationLogId,String transferInDateTime) {

        List<String> isAllFinish = circulationTemplateMapper.checkIsFinish(inpatNum, "in_dept");
        if (null != isAllFinish && isAllFinish.size() > 0) {
            return ResultGenerator.genFailedResult(StringUtils.join(isAllFinish.toArray()) + "未完成，无法保存");
        }

        List<Map<String, String>> rotatingList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.INCOMPLETE.getValue(), CirculationTypeEnum.TRANSFERRED_DEPT.getCode(), CirculationModelEnum.WAIT_IN_DEPT.getCode(), null, circulationLogId);//获取待转入日志
        try {
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            if (rotatingList == null || rotatingList.size() <= 0)
                return ResultGenerator.genFailedResult("此病人无待转入记录");
            for (Map<String, String> rotating : rotatingList) {
                String deptId = rotating.get("IN_DEPT_ID");
                if (StringUtils.isBlank(deptId))
                    return ResultGenerator.genFailedResult("数据异常,日志中无转入科室");

                Map<String, String> patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, rotating.get("CIRCULATION_LOG_ID"));
                //his接口
                //调用转科his接口
                /*Map<String, Object> param = new HashMap<>();
                //病人编码 住院号
                param.put("p_patient_id", patient.get("medicalNum"));
                //就诊次数 住院号-后的值
                param.put("p_visit_id", patient.get("inpatTimes"));
                //床号
                param.put("p_bed_no", bedNo);
                //科室代码
                param.put("p_dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("IN_DEPT_ID")));
                //病区代码
                param.put("p_ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("IN_WARD_DEPT_ID")));
                //入院时间
                param.put("p_in_date", patient.get("inTime"));
                //转入时间
                param.put("p_in_dept_date", DateUtil.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
                //责任医生
                param.put("p_doctor", patientInHospitalMapper.queryUserIdByPersonId(doctorPersonId));
                //责任护士
                param.put("p_nurse", patientInHospitalMapper.queryUserIdByPersonId(nurseId));
                //入科操作码
                param.put("operationID", ConstantEnum.HIS_CIRCULATION_10032.getKey());

                System.out.println(JSON.toJSONString(param));
                JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
                if(jsonObject.isEmpty()){
                    return ResultGenerator.genFailedResult("患者转科转入失败");
                }
                Integer resInt = Integer.valueOf((String)jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    //return ResultGenerator.genFailedResult("HIS接口调用失败");
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }*/

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //circulationLogMapper.updateLogStatusById(rotating.get("CIRCULATION_LOG_ID"), sdf.format(new Date()), null, StateEnum.COMPLETED.getValue(),userId);//更新日志状态
                circulationLogMapper.updateLogStatusById(rotating.get("CIRCULATION_LOG_ID"), transferInDateTime+":00", null, StateEnum.COMPLETED.getValue(),userId);//更新日志状态


                //circulationLogMapper.updatePatient(inpatNum, bedNo, deptId, patient.get("inWardId"),doctorPersonId,nurseId);
                CirculationLogEntity entity2 = new CirculationLogEntity();//已转入日志
                entity2.initAdd();
                entity2.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));//已完成
                entity2.setCirculationLogId(UUIDUtil.randomString());
                entity2.setCirculationModelType(CirculationModelEnum.FINISH_IN_DEPT.getCode());
                entity2.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
                entity2.setInpatNum(inpatNum);
                entity2.setOutDatetime(new Timestamp(sdf.parse(rotating.get("outTime")).getTime()));
                //entity2.setInDatetime(new Date());
                entity2.setInDatetime(DateUtil.stringToDate(transferInDateTime+":00","yyyy-MM-dd HH:mm:ss"));
                entity2.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
                entity2.setInDeptId(rotating.get("IN_DEPT_ID"));
                entity2.setOutDeptId(rotating.get("OUT_DEPT_ID"));
                entity2.setSourceType("SELF");
                entity2.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                //entity2.setSerialNo(1);
                entity2.setSerialNo(rotating.get("serialNo") == null ? 1 : (Integer.parseInt(rotating.get("serialNo"))) + 1);
                entity2.setCancelFlag(0);
                entity2.setRemark(transport);
                entity2.setPatTypeId(rotating.get("PAT_TYPE_ID"));
                entity2.setHealthNum(rotating.get("HEALTH_NUM"));
                entity2.setOutDoctorPersonId(rotating.get("OUT_DOCTOR_PERSON_ID"));
                //entity2.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                entity2.setInDoctorPersonId(doctorPersonId);
                //entity2.setInBedNo(rotating.get("IN_BED_NO"));
                entity2.setInBedNo(bedNo);
                entity2.setInBedLabel(circulationLogMapper.queryBedLabel(rotating.get("IN_WARD_DEPT_ID"),bedNo));
                entity2.setOutBedNo(rotating.get("OUT_BED_NO"));
                entity2.setOutBedLabel(rotating.get("OUT_BED_LABEL"));
                entity2.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity2.setOutWardDeptId(rotating.get("OUT_WARD_DEPT_ID"));
                //entity2.setInNurseTd(rotating.get("IN_NURSE_ID"));
                entity2.setInNurseId(nurseId);
                entity2.setRemark(rotating.get("REMARK")==null?null:rotating.get("REMARK"));
                entity2.setOutNurseId(rotating.get("OUT_NURSE_ID"));
                entity2.setOperator(userId);
                circulationLogMapper.insert(entity2);

                //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
                List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(rotating.get("CIRCULATION_LOG_ID"));
                //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
                if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                    commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, entity2.getCirculationLogId());
                }
                //更新床位状态
                //circulationLogMapper.updateBedNoStatus(bedNo,rotatingList.get(0).get("IN_WARD_DEPT_ID"),"1");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转科转入失败" + e.getMessage());
            return ResultGenerator.genFailedResult("转科转入失败");
        }

        //等待请求his todo
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result getTransport() {
        return ResultGenerator.genOkResult(circulationLogMapper.getTransport("1a6fa8ca6dd04d33b48b52e9a9882058"));
    }


    @Override
    public Result getOptions(String dataId) {
        List<Map<String, String>> result = circulationLogMapper.getOptions(dataId);
        return ResultGenerator.genOkResult(result);
    }


    @Transactional(rollbackFor = Exception.class)
    public Result patientCancelLeaveHospital(String inpatNum, String bedNo,String circulationLogId) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        PatientInHospitalEntity patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
        if (patientInHospitalEntity == null) {
            return ResultGenerator.genFailedResult("无此病人信息！");
        }

        //需增加判断（未结账）  如果未结账 可以取消出院  已结账 不可以取消出院
        boolean isCharge = queryPatientSettlement(patientInHospitalEntity.getMedicalNum(), patientInHospitalEntity.getInpatTimes());

        if (isCharge) {
            return ResultGenerator.genFailedResult("此病人已出院不能取消！");
        }

        //增加待出院入院日志
        CirculationLogEntity outCirculationLogEntity = null;
        if(StringUtils.isNotBlank(circulationLogId)) {
            outCirculationLogEntity = circulationLogMapper.selectNewLogByInpatNum(inpatNum, circulationLogId);
            if (outCirculationLogEntity == null) {
                return ResultGenerator.genFailedResult("此病人已出院流转记录！");
            }
        }

        // 取消出院his接口调用
        Map<String, Object> param = new HashMap<>();
        //病人编码 住院号
        param.put("p_patient_id", patientInHospitalEntity.getMedicalNum());
        //就诊次数 住院号-后的值
        param.put("p_visit_id", patientInHospitalEntity.getInpatTimes());
        //床号
        //param.put("p_bed_no", outCirculationLogEntity.getOutBedNo());
        param.put("p_bed_no", bedNo);
        //操作取消的病区代码
        param.put("p_ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(patientInHospitalEntity.getWardDeptId()));
        //操作取消的科室代码
        param.put("p_dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(patientInHospitalEntity.getDeptId()));
        //取消出院操作码
        param.put("operationID", ConstantEnum.HIS_CIRCULATION_10039.getKey());

        System.out.println(JSON.toJSONString(param));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
        if (jsonObject.isEmpty()) {
            return ResultGenerator.genFailedResult("患者取消出院失败");
        }
        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
        if (resInt < 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //return ResultGenerator.genFailedResult("HIS接口调用失败");
            return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
        }

        //his对接 取消操作后，病人信息回到病人流转操作前的状态：例：一键停止的医嘱自动取消，为未停止状态


        if(StringUtils.isNotBlank(circulationLogId)) {
            //先已完成修改状态
            circulationLogMapper.updateCancel(outCirculationLogEntity.getCirculationLogId(), userId);
        }

        Map<String, String> nurseInfo = circulationLogMapper.queryDeptByInpatNum(inpatNum);
        String nurseId = null;
        if(nurseInfo!=null){
            nurseId = nurseInfo.get("nurseId");
        }

        CirculationLogEntity circulationLogEntity = new CirculationLogEntity();
        circulationLogEntity.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));
        Timestamp currentTime = new Timestamp(new Date().getTime());
        circulationLogEntity.setCirculationLogId(UUIDUtil.randomString());
        circulationLogEntity.setCreateTime(currentTime);
        circulationLogEntity.setModifyTime(currentTime);
        circulationLogEntity.setHospitalId(patientInHospitalEntity.getHospitalId());
        circulationLogEntity.setCirculationOperateType(CirculationTypeEnum.OUT_HOSP.getCode());

        circulationLogEntity.setInpatNum(patientInHospitalEntity.getInpatNum());
        circulationLogEntity.setCancelFlag(0);

        if (null != outCirculationLogEntity) {
            circulationLogEntity.setInpatorderdataId(outCirculationLogEntity.getInpatorderdataId());
            circulationLogEntity.setSerialNo(outCirculationLogEntity.getSerialNo() + 1);
            circulationLogEntity.setOutDatetime(outCirculationLogEntity.getOutDatetime());
            circulationLogEntity.setDataVersion(outCirculationLogEntity.getDataVersion());
            //circulationLogEntity.setOutBedNo(outCirculationLogEntity.getOutBedNo());
            circulationLogEntity.setOutBedNo(bedNo);
            circulationLogEntity.setOutBedNo(circulationLogMapper.queryBedLabel(patientInHospitalEntity.getWardDeptId(),bedNo));
            circulationLogEntity.setBatchNo(outCirculationLogEntity.getBatchNo());
        }else{
            String inpatorderdataId = circulationLogMapper.queryPatientOrdersByInpatNum(inpatNum);
            //获取医嘱id
            circulationLogEntity.setInpatorderdataId(inpatorderdataId);
            circulationLogEntity.setSerialNo(1);
            circulationLogEntity.setOutDatetime(patientInHospitalEntity.getOutDatetime());
            circulationLogEntity.setDataVersion(1);
            circulationLogEntity.setBatchNo(1);
        }

        circulationLogEntity.setCirculationModelType(CirculationModelEnum.CANCLE_OUT_HOSP.getCode());

        circulationLogEntity.setHealthNum(patientInHospitalEntity.getHealthNum());
        circulationLogEntity.setOutpatNum(patientInHospitalEntity.getOutpatNum());
        circulationLogEntity.setPatTypeId(patientInHospitalEntity.getPatTypeId());

        circulationLogEntity.setOutWardDeptId(patientInHospitalEntity.getWardDeptId());
        circulationLogEntity.setOutDeptId(patientInHospitalEntity.getDeptId());

        circulationLogEntity.setOutNurseId(nurseId);
        circulationLogEntity.setOutDoctorPersonId(patientInHospitalEntity.getResponsibleDoctorPersonId());

        circulationLogEntity.setSourceType(Constant.SELF);
        circulationLogEntity.setCirculationModelType(CirculationModelEnum.CANCLE_OUT_HOSP.getCode());
        circulationLogEntity.setOperator(userId);

        circulationLogMapper.insert(circulationLogEntity);

        //更改病人信息为待出院，增加待出院日志
        CirculationLogEntity waitCirculationLogEntity = new CirculationLogEntity();
        BeanUtils.copyProperties(circulationLogEntity, waitCirculationLogEntity);

        waitCirculationLogEntity.setSerialNo(circulationLogEntity.getSerialNo() + 1);
        waitCirculationLogEntity.setBatchNo(circulationLogEntity.getBatchNo() == null ? 1 : circulationLogEntity.getBatchNo() + 1);

        waitCirculationLogEntity.setStatus(Integer.parseInt(StateEnum.INCOMPLETE.getValue()));
        waitCirculationLogEntity.setCirculationModelType(CirculationModelEnum.WAIT_OUT_HOSP.getCode());
        waitCirculationLogEntity.setCirculationLogId(UUIDUtil.randomString());
        waitCirculationLogEntity.setOutDatetime(null);
        waitCirculationLogEntity.setOutBedNo(bedNo);
        circulationLogEntity.setOutBedNo(circulationLogMapper.queryBedLabel(patientInHospitalEntity.getWardDeptId(),bedNo));
        waitCirculationLogEntity.setOperator(userId);
        circulationLogMapper.insert(waitCirculationLogEntity);

        // 修改病人信息表中的出院相关信息
        if (patientInHospitalEntity != null) {
            //设置出院时间、出院科室代码、出院病区、出院病房
            patientInHospitalEntity.setOutDatetime(null);
            patientInHospitalEntity.setOutDeptId(null);
            patientInHospitalEntity.setOutWardDeptId(null);
            patientInHospitalEntity.setOutRoomNo(null);
            patientInHospitalEntity.setBedNo(bedNo);
            //设置OUT_DEPT_ID
            patientInHospitalEntity.setGmtModify(currentTime);
            //实际住院天数
            patientInHospitalMapper.updateByPrimaryKey(patientInHospitalEntity);
        }

        if(StringUtils.isNotBlank(circulationLogId)) {
            //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
            List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(outCirculationLogEntity.getCirculationLogId());
            //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
            if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, waitCirculationLogEntity.getCirculationLogId());
            }
        }

        //更新床位状态
        circulationLogMapper.updateBedNoStatus(bedNo, patientInHospitalEntity.getWardDeptId(), "1");

        return ResultGenerator.genOkResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result patientTransferOutCancel(String inpatNum, String bedNo,String circulationLogId) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<Map<String, String>> rotatingList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.COMPLETED.getValue(), CirculationTypeEnum.TRANSFERRED_DEPT.getCode(), CirculationModelEnum.FINISH_OUT_DEPT.getCode(), null, circulationLogId);//获取待转出日志
        try {
            if (rotatingList == null || rotatingList.size() <= 0) {
                return ResultGenerator.genFailedResult("此病人无转出记录");
            }

            PatientInHospitalEntity patientInHospitalInfo = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
            Map<String, Object> param = new HashMap<>();
            //病人编码 住院号
            param.put("p_patient_id", patientInHospitalInfo.getMedicalNum());
            //就诊次数 住院号-后的值
            param.put("p_visit_id", patientInHospitalInfo.getInpatTimes());
            //床号
            //param.put("p_bed_no", rotatingList.get(0).get("OUT_BED_NO"));
            param.put("p_bed_no", bedNo);
            //原病区代码
            param.put("p_ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("OUT_WARD_DEPT_ID")));
            //原科室代码
            param.put("p_dept_code_in", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("OUT_DEPT_ID")));
            //取消转出科室操作码
            param.put("operationID", ConstantEnum.HIS_CIRCULATION_10037.getKey());
            System.out.println(JSON.toJSONString(param));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
            if (jsonObject.isEmpty()) {
                return ResultGenerator.genFailedResult("患者取消转科转出失败");
            }
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //return ResultGenerator.genFailedResult("HIS接口调用失败");
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            }

            String iId = rotatingList.get(0).get("INPATORDERDATA_ID");
            List<Map<String, String>> finishList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.COMPLETED.getValue(), CirculationTypeEnum.
                    TRANSFERRED_DEPT.getCode(), CirculationModelEnum.FINISH_OUT_DEPT.getCode(), iId, null);//已完成
            List<Map<String, String>> waitList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.INCOMPLETE.getValue(),
                    CirculationTypeEnum.TRANSFERRED_DEPT.getCode(), CirculationModelEnum.WAIT_IN_DEPT.getCode(), iId, null);//待入科

            List<Map<String, String>> finishInList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.COMPLETED.getValue(), CirculationTypeEnum.
                    TRANSFERRED_DEPT.getCode(), CirculationModelEnum.FINISH_IN_DEPT.getCode(), iId, null);//已转入
            if (finishInList != null && finishInList.size() > 0) {
                return ResultGenerator.genFailedResult("病人已转入,不可取消");
            }

            if (finishList != null && finishList.size() > 0) {
                circulationLogMapper.updateCancel(finishList.get(0).get("CIRCULATION_LOG_ID"),userId);
            }

            if (waitList != null && waitList.size() > 0) {
                circulationLogMapper.updateCancel(waitList.get(0).get("CIRCULATION_LOG_ID"),userId);
            }

            for (Map<String, String> rotating : rotatingList) {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                CirculationLogEntity entity2 = new CirculationLogEntity();//插入取消数据
                entity2.initAdd();
                entity2.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));//已完成
                entity2.setCirculationLogId(UUIDUtil.randomString());
                entity2.setCirculationModelType(CirculationModelEnum.CANCLE_OUT_DEPT.getCode());
                entity2.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
                entity2.setInpatNum(inpatNum);
                if (rotating.get("outTime") != null) {
                    entity2.setOutDatetime(new Timestamp(sdf.parse(rotating.get("outTime")).getTime()));
                }
                if (rotating.get("inTime") != null) {
                    entity2.setInDatetime(new Timestamp(sdf.parse(rotating.get("inTime")).getTime()));
                }
                entity2.setInDeptId(rotating.get("IN_DEPT_ID"));
                entity2.setOutDeptId(rotating.get("OUT_DEPT_ID"));
                entity2.setSourceType("SELF");
                //entity2.setSerialNo(1);
                entity2.setSerialNo(rotating.get("serialNo") == null ? 1 : (Integer.parseInt(rotating.get("serialNo"))) + 1);
                entity2.setCancelFlag(0);
                entity2.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity2.setRemark(rotating.get("REMARK"));
                entity2.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
                entity2.setPatTypeId(rotating.get("PAT_TYPE_ID"));
                entity2.setHealthNum(rotating.get("HEALTH_NUM"));
                entity2.setOutDoctorPersonId(rotating.get("OUT_DOCTOR_PERSON_ID"));
                entity2.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                entity2.setInBedNo(rotating.get("IN_BED_NO"));
                entity2.setInBedLabel(rotating.get("IN_BED_LABEL"));
                //entity2.setOutBedNo(rotating.get("OUT_BED_NO"));
                entity2.setOutBedNo(bedNo);
                entity2.setOutBedLabel(circulationLogMapper.queryBedLabel(rotating.get("OUT_WARD_DEPT_ID"),bedNo));
                entity2.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity2.setOutWardDeptId(rotating.get("OUT_WARD_DEPT_ID"));
                entity2.setInNurseId(rotating.get("IN_NURSE_ID"));
                entity2.setOutNurseId(rotating.get("OUT_NURSE_ID"));
                entity2.setOperator(userId);
                circulationLogMapper.insert(entity2);

                CirculationLogEntity entity3 = new CirculationLogEntity();//待转入新增
                entity3.initAdd();
                entity3.setStatus(Integer.parseInt(StateEnum.INCOMPLETE.getValue()));
                entity3.setCirculationLogId(UUIDUtil.randomString());
                entity3.setCirculationModelType(CirculationModelEnum.WAIT_OUT_DEPT.getCode());
                entity3.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
                entity3.setInpatNum(inpatNum);
                if (rotating.get("outTime") != null) {
                    entity3.setOutDatetime(new Timestamp(sdf.parse(rotating.get("outTime")).getTime()));
                }
                if (rotating.get("inTime") != null) {
                    entity3.setInDatetime(new Timestamp(sdf.parse(rotating.get("inTime")).getTime()));
                }
                entity3.setInDeptId(rotating.get("IN_DEPT_ID"));
                entity3.setOutDeptId(rotating.get("OUT_DEPT_ID"));
                entity3.setSourceType("SELF");
                //entity3.setSerialNo(1);
                entity3.setSerialNo(entity2.getSerialNo() + 1);
                entity3.setCancelFlag(0);
                entity3.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity3.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
                entity3.setRemark(rotating.get("REMARK"));
                entity3.setPatTypeId(rotating.get("PAT_TYPE_ID"));
                entity3.setHealthNum(rotating.get("HEALTH_NUM"));
                entity3.setOutDoctorPersonId(rotating.get("OUT_DOCTOR_PERSON_ID"));
                entity3.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                entity3.setInBedNo(rotating.get("IN_BED_NO"));
                entity3.setInBedLabel(rotating.get("IN_BED_LABEL"));
                //entity3.setOutBedNo(rotating.get("OUT_BED_NO"));
                entity3.setOutBedNo(bedNo);
                entity2.setOutBedLabel(circulationLogMapper.queryBedLabel(rotating.get("OUT_WARD_DEPT_ID"),bedNo));
                entity3.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity3.setOutWardDeptId(rotating.get("OUT_WARD_DEPT_ID"));
                entity3.setInNurseId(rotating.get("IN_NURSE_ID"));
                entity3.setOutNurseId(rotating.get("OUT_NURSE_ID"));
                entity3.setOperator(userId);
                circulationLogMapper.insert(entity3);

                //更新病人信息表
                circulationLogMapper.updatePatientOut(inpatNum, bedNo, rotatingList.get(0).get("OUT_DEPT_ID"), rotatingList.get(0).get("OUT_WARD_DEPT_ID"));

                //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
                if (finishList != null && finishList.size() > 0) {
                    List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(finishList.get(0).get("CIRCULATION_LOG_ID"));
                    //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
                    if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                        commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, entity3.getCirculationLogId());
                    }
                }

                //更新床号 原床状态为0
                circulationLogMapper.updateBedNoStatus(bedNo, rotatingList.get(0).get("OUT_WARD_DEPT_ID"), "1");

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转科转出取消失败失败" + e.getMessage());
            return ResultGenerator.genFailedResult("转科转出取消失败失败");
        }

        return ResultGenerator.genOkResult();
    }

    @Override
    public Result outCanCancel(String inpatNum,String circulationLogId) {
        List<Map<String, String>> rotatingList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.COMPLETED.getValue(), CirculationTypeEnum.TRANSFERRED_DEPT.getCode(), CirculationModelEnum.FINISH_OUT_DEPT.getCode(), null, circulationLogId);//获取待转出日志
        String iId = rotatingList.get(0).get("INPATORDERDATA_ID");
        List<Map<String, String>> finishInList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.COMPLETED.getValue(), CirculationTypeEnum.
                TRANSFERRED_DEPT.getCode(), CirculationModelEnum.FINISH_IN_DEPT.getCode(), iId, null);//已转入
        if (finishInList != null && finishInList.size() > 0) {
            return ResultGenerator.genFailedResult("病人已转入,不可取消");
        }
        return ResultGenerator.genOkResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result patientTransferInCancel(String inpatNum,String circulationLogId) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<Map<String, String>> rotatingList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.COMPLETED.getValue(), CirculationTypeEnum.TRANSFERRED_DEPT.getCode(), CirculationModelEnum.FINISH_IN_DEPT.getCode(), null, circulationLogId);//获取待转出日志
        try {
            if (rotatingList == null || rotatingList.size() <= 0)
                return ResultGenerator.genFailedResult("此病人无转入记录");

            PatientInHospitalEntity patientInHospitalInfo = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
            //缺his接口
            Map<String, Object> param = new HashMap<>();
            //病人编码 住院号
            param.put("p_patient_id", patientInHospitalInfo.getMedicalNum());
            //就诊次数 住院号-后的值
            param.put("p_visit_id", patientInHospitalInfo.getInpatTimes());
            //床号
            param.put("p_bed_no", rotatingList.get(0).get("IN_BED_NO"));
            //原病区代码
            param.put("p_ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("IN_WARD_DEPT_ID")));
            //原科室代码
            param.put("p_dept_code_in", patientInHospitalMapper.queryDeptCodeByDeptId(rotatingList.get(0).get("IN_DEPT_ID")));
            //取消转出科室操作码
            param.put("operationID", ConstantEnum.HIS_CIRCULATION_10036.getKey());
            System.out.println(JSON.toJSONString(param));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
            if (jsonObject.isEmpty()) {
                return ResultGenerator.genFailedResult("患者取消转科转入失败");
            }
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //return ResultGenerator.genFailedResult("HIS接口调用失败");
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            }


            String iId = rotatingList.get(0).get("INPATORDERDATA_ID");
            List<Map<String, String>> finishList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.COMPLETED.getValue(), CirculationTypeEnum.
                    TRANSFERRED_DEPT.getCode(), CirculationModelEnum.FINISH_IN_DEPT.getCode(), iId, null);//已完成

            if (finishList != null && finishList.size() > 0) {
                circulationLogMapper.updateCancel(finishList.get(0).get("CIRCULATION_LOG_ID"),userId);
            }

            for (Map<String, String> rotating : rotatingList) {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                CirculationLogEntity entity2 = new CirculationLogEntity();//插入取消数据
                entity2.initAdd();
                entity2.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));//已完成
                entity2.setCirculationLogId(UUIDUtil.randomString());
                entity2.setCirculationModelType(CirculationModelEnum.CANCLE_IN_DEPT.getCode());
                entity2.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
                entity2.setInpatNum(inpatNum);
                if (rotating.get("outTime") != null) {
                    entity2.setOutDatetime(new Timestamp(sdf.parse(rotating.get("outTime")).getTime()));
                }
                if (rotating.get("inTime") != null) {
                    entity2.setInDatetime(new Timestamp(sdf.parse(rotating.get("inTime")).getTime()));
                }
                entity2.setInDeptId(rotating.get("IN_DEPT_ID"));
                entity2.setOutDeptId(rotating.get("OUT_DEPT_ID"));
                entity2.setSourceType("SELF");
                //entity2.setSerialNo(1);
                entity2.setSerialNo(rotating.get("serialNo") == null ? 1 : (Integer.parseInt(rotating.get("serialNo"))) + 1);

                entity2.setCancelFlag(0);
                entity2.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
                entity2.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity2.setRemark(rotating.get("REMARK"));
                entity2.setPatTypeId(rotating.get("PAT_TYPE_ID"));
                entity2.setHealthNum(rotating.get("HEALTH_NUM"));
                entity2.setOutDoctorPersonId(rotating.get("OUT_DOCTOR_PERSON_ID"));
                entity2.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                entity2.setInBedNo(rotating.get("IN_BED_NO"));
                entity2.setInBedLabel(rotating.get("IN_BED_LABEL"));
                entity2.setOutBedNo(rotating.get("OUT_BED_NO"));
                entity2.setOutBedLabel(rotating.get("OUT_BED_LABEL"));
                entity2.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity2.setOutWardDeptId(rotating.get("OUT_WARD_DEPT_ID"));
                entity2.setInNurseId(rotating.get("IN_NURSE_ID"));
                entity2.setOperator(userId);

                circulationLogMapper.insert(entity2);

                CirculationLogEntity entity3 = new CirculationLogEntity();//待转入新增
                entity3.initAdd();
                entity3.setStatus(Integer.parseInt(StateEnum.INCOMPLETE.getValue()));
                entity3.setCirculationLogId(UUIDUtil.randomString());
                entity3.setCirculationModelType(CirculationModelEnum.WAIT_IN_DEPT.getCode());
                entity3.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
                entity3.setInpatNum(inpatNum);
                if (rotating.get("outTime") != null) {
                    entity3.setOutDatetime(new Timestamp(sdf.parse(rotating.get("outTime")).getTime()));
                }
                if (rotating.get("inTime") != null) {
                    entity3.setInDatetime(new Timestamp(sdf.parse(rotating.get("inTime")).getTime()));
                }
                entity3.setInDeptId(rotating.get("IN_DEPT_ID"));
                entity3.setOutDeptId(rotating.get("OUT_DEPT_ID"));
                entity3.setSourceType("SELF");
                //entity3.setSerialNo(1);
                entity3.setSerialNo(entity2.getSerialNo() + 1);
                entity3.setInpatorderdataId(rotating.get("INPATORDERDATA_ID"));
                entity3.setCancelFlag(0);
                entity3.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity3.setRemark(rotating.get("REMARK"));
                //entity3.setInBedNo(bedNo);
                entity3.setPatTypeId(rotating.get("PAT_TYPE_ID"));
                entity3.setHealthNum(rotating.get("HEALTH_NUM"));
                entity3.setOutDoctorPersonId(rotating.get("OUT_DOCTOR_PERSON_ID"));
                //entity3.setInDoctorPersonId(rotating.get("IN_DOCTOR_PERSON_ID"));
                //entity3.setInBedNo(rotating.get("IN_BED_NO"));
                entity3.setOutBedNo(rotating.get("OUT_BED_NO"));
                entity3.setOutBedLabel(rotating.get("OUT_BED_LABEL"));
                entity3.setInWardDeptId(rotating.get("IN_WARD_DEPT_ID"));
                entity3.setOutWardDeptId(rotating.get("OUT_WARD_DEPT_ID"));
                entity3.setOperator(userId);
                //entity3.setInNurseTd(rotating.get("IN_NURSE_ID"));
                circulationLogMapper.insert(entity3);

                //更新病人信息表
                circulationLogMapper.updatePatientOut(inpatNum, null, null, null);

                //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
                if (finishList != null && finishList.size() > 0) {
                    List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(finishList.get(0).get("CIRCULATION_LOG_ID"));
                    //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
                    if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                        commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, entity3.getCirculationLogId());
                    }
                }
                //更新床位状态
                circulationLogMapper.updateBedNoStatus(rotatingList.get(0).get("IN_BED_NO"), rotatingList.get(0).get("IN_WARD_DEPT_ID"), "0");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转科转入取消失败失败" + e.getMessage());
            return ResultGenerator.genFailedResult("转科转入取消失败失败");
        }

        return ResultGenerator.genOkResult();
    }

    private UserEntity getCurrentUser() {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        UserEntity currentUser = userMapper.selectByPrimaryKey(userId);
        return currentUser;
    }

    /**
     * 获取病区对应的所有医生
     *
     * @param wardDeptId
     * @return
     */
    public Result queryNurseListByWardDeptId(String wardDeptId) {
        return ResultGenerator.genOkResult(circulationLogMapper.queryNurseListByWardDeptId(wardDeptId,null,null));
    }

    /**
     * 获取病区对应的所有医生
     *
     * @param wardDeptId
     * @return
     */
    public Result queryNurseListByWardDeptId2(String wardDeptId,String id,Integer page,Integer pageSize,String keyWords) {
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = circulationLogMapper.queryNurseListByWardDeptId(wardDeptId, id,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    /**
     * @param circulationLogId
     * @return
     */
    public Result queryPatientOperationByCirculationLogId(String circulationLogId) {
        Map<String, String> patientOperationMap = new HashMap<String, String>();

        CirculationLogDTO circulationLogEntity = circulationLogMapper.queryDtoCirculationLogById(circulationLogId);
        if (circulationLogEntity != null) {
            if (CirculationTypeEnum.OPERATION.getCode().equals(circulationLogEntity.getCirculationOperateType())) {
                Map<String, String> operation = circulationLogMapper.queryPatientOperationByInpatorderdataId(circulationLogEntity.getInpatorderdataId());
                if (StringUtils.isNotBlank(circulationLogEntity.getRemark())) {
                    patientOperationMap = JSONObject.parseObject(circulationLogEntity.getRemark(), Map.class);
                    patientOperationMap.put("SCHEDULED_DATE_TIME", patientOperationMap.get("SCHEDULED_DATE_TIME").substring(0, 16));
                    patientOperationMap.put("ARRANGE_DATE_TIME", patientOperationMap.get("ARRANGE_DATE_TIME").substring(0, 16));
                } else {
                    PatientInHospitalEntity patientInHospitalInfo = patientInHospitalMapper.selectPatientByInpatNum(circulationLogEntity.getInpatNum());
                    String operationTime = circulationLogMapper.queryOperationTime(circulationLogEntity.getInpatorderdataId());
                    //his对接
                    Map<String, Object> param = new HashMap<>();
                    //病人编码 住院号
                    param.put("p_patient_id", patientInHospitalInfo.getMedicalNum());
                    //就诊次数 住院号-后的值
                    param.put("p_visit_id", patientInHospitalInfo.getInpatTimes());
                    //排序字段及方向
                    param.put("p_sort", "");
                    //当前页-默认第一页
                    param.put("p_curPage", "1");
                    //每页行数-默认每页10行
                    param.put("p_pageSize", "10");
                    //手术操作码
                    param.put("operationID", ConstantEnum.HIS_CIRCULATION_10046.getKey());
                    System.out.println(JSON.toJSONString(param));

                    JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
                    if (jsonObject.isEmpty()) {
                        return ResultGenerator.genFailedResult("手术获取数据失败");
                    }
                    Integer resInt = Integer.valueOf((String) jsonObject.get("p_totalRecords"));
                    if (resInt < 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        //return ResultGenerator.genFailedResult("HIS接口调用失败");
                        return ResultGenerator.genFailedResult("手术获取数据失败");
                    }
                    if (jsonObject.getString("data") != null) {
                        List<Map> list = JSONArray.parseArray(jsonObject.getString("data"), Map.class);
                        /*if(list.size()==1){
                            patientOperationMap = list.get(0);
                            patientOperationMap.put("SCHEDULED_DATE_TIME",patientOperationMap.get("SCHEDULED_DATE_TIME").substring(0,16));
                        }else if(list.size()>1){
                            patientOperationMap = list.stream().filter(operationData->operationTime.equals(operationData.get("SCHEDULED_DATE_TIME"))).findFirst().orElse(null);
                            patientOperationMap.put("SCHEDULED_DATE_TIME",patientOperationMap.get("SCHEDULED_DATE_TIME").substring(0,16));

                        }*/
                        /*if(list!=null && list.size()>=1){
                            patientOperationMap = list.get(0);
                            patientOperationMap.put("SCHEDULED_DATE_TIME",patientOperationMap.get("SCHEDULED_DATE_TIME").substring(0,16));
                            patientOperationMap.put("ARRANGE_DATE_TIME",patientOperationMap.get("ARRANGE_DATE_TIME").substring(0,16));
                        }*/
                        if (list != null && list.size() > 0) {
                            for (Map oMap : list) {
                                if (CommonUtils.isNotEmpty((String) oMap.get("OPERATING_ROOM_NO")) && CommonUtils.isNotEmpty((String) oMap.get("ARRANGE_DATE_TIME"))) {
                                    if ((oMap.get("OPERATION")).equals(operation.get("operationName")) && operationTime.equals(oMap.get("SCHEDULED_DATE_TIME"))) {
                                        patientOperationMap = oMap;
                                        patientOperationMap.put("SCHEDULED_DATE_TIME", patientOperationMap.get("SCHEDULED_DATE_TIME").substring(0, 16));
                                        patientOperationMap.put("ARRANGE_DATE_TIME", patientOperationMap.get("ARRANGE_DATE_TIME").substring(0, 16));
                                    }
                                }
                            }
                        }
                    }
                }
                patientOperationMap.putAll(operation);
                patientOperationMap.put("gmtModify", circulationLogEntity.getUpdateTime());
                patientOperationMap.put("circulationLogId", circulationLogEntity.getCirculationLogId());
                patientOperationMap.put("inWardDeptName", circulationLogEntity.getInWardDeptName());
                patientOperationMap.put("outWardDeptName", circulationLogEntity.getOutWardDeptName());
                return ResultGenerator.genOkResult(patientOperationMap);
            } else if (CirculationTypeEnum.IN_HOSP.getCode().equals(circulationLogEntity.getCirculationOperateType())) {
                //获取his门诊诊断
                String diagName = circulationLogMapper.queryOutpatientDiag2(circulationLogEntity.getInpatNum());
                if(StringUtils.isNotBlank(diagName)){
                    circulationLogEntity.setDiagName(diagName);
                }else{
                    diagName = circulationLogMapper.queryOutpatientDiag(circulationLogEntity.getInpatNum());
                    if(StringUtils.isNotBlank(diagName)){
                        circulationLogEntity.setDiagName(diagName);
                    }
                }
                return ResultGenerator.genOkResult(circulationLogEntity);
            } else {
                // 过滤诊断
                // 获取护士修改后绑定到文书的诊断id
                String diagName = "";
                String diagId = circulationLogMapper.queryDiagIdByInpatNum(circulationLogEntity.getInpatNum());
                if (org.apache.commons.lang3.StringUtils.isNotBlank(diagId)) {
                    // 获取护士修改的诊断名称
                    diagName = circulationLogMapper.queryDiagByDiagId(diagId);
                    circulationLogEntity.setDiagName(diagName);
                } else {
                    //取病案首页his出院诊断
                    if ("prod".equals(activeType)) {
                        String[] inpatNums = circulationLogEntity.getInpatNum().split("-");
                        String param = "as_patient_id=" + inpatNums[0] + "&al_visit_id=" + inpatNums[1];
                        JSONObject jsonObject = HttpConnectUtils.sendGet("http://172.20.91.56:8181/P_VsitInfo_Query_03", param);
                        if ("1".equals(jsonObject.get("error_id").toString())) {
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            for (Object jsonObject1 : jsonArray) {
                                JSONObject object = JSONObject.parseObject(jsonObject1.toString());
                                if (object.get("DIAGNOSIS_TYPE") != null && "2".equals(object.get("DIAGNOSIS_TYPE").toString())) {
                                    diagName = object.get("DIAGNOSIS_DESC").toString();
                                    break;
                                }
                            }
                        }
                    }
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(diagName)) {
                        circulationLogEntity.setDiagName(diagName);
                    } else {
                        // 获取智慧病历出院诊断/修正诊断/入院诊断
                        diagName = circulationLogMapper.queryOutHospitalDiag(circulationLogEntity.getInpatNum());
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(diagName)) {
                            circulationLogEntity.setDiagName(diagName);
                        } else {
                            //获取his门诊诊断
                            diagName = circulationLogMapper.queryOutpatientDiag(circulationLogEntity.getInpatNum());
                            circulationLogEntity.setDiagName(diagName);
                        }
                    }
                }

                return ResultGenerator.genOkResult(circulationLogEntity);
            }

        }
        return ResultGenerator.genOkResult();

    }

    public Result savePatientInfoInHosp(Map<String, Object> params) {
        String inpatNum = (String) params.get("inpatNum");
        String bedNo = (String) params.get("bedNo");
        String deptId = (String) params.get("deptId");
        String deptName = (String) params.get("deptName");
        String doctorPerson = (String) params.get("doctorPerson");
        String doctorPersonId = (String) params.get("doctorPersonId");
        String inDatetime = (String) params.get("inDatetime");
        String nurseId = (String) params.get("nurseId");
        String nurseName = (String) params.get("nurseName");
        String wardDeptId = (String) params.get("wardDeptId");
        String circulationLogId = (String) params.get("circulationLogId");
        String editFlag = (String) params.get("editFlag");

        /*if (StringUtils.isNotEmpty(editFlag) && "1".equals(editFlag)) {
            return ResultGenerator.genOkResult(params);
        } else {*/
            //1.调用HIS接口
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
            UserEntity currentUser = userMapper.selectByPrimaryKey(userId);
            PatientInHospitalEntity patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
            //查询医生对应的emp_no,dept_code,诊断名称，诊断ICD，责任护士工号
            Map<String, String> res = patientInHospitalMapper.queryPatientOtherInfo(inpatNum);
            //根据用户id获取工号
            //1.调用HIS接口
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> requestMap = new HashMap<>();
            Map<String, Object> param = new HashMap<>();
            param.put("patient_id", patientInHospitalEntity.getMedicalNum());
            param.put("visit_id", patientInHospitalEntity.getInpatTimes());
            param.put("operator", currentUser.getUserName());
            param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
            param.put("dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(deptId));
            param.put("bed_no", Integer.valueOf(bedNo));
            //param.put("admission_date_time", DateUtil.dateToString(patientInHospitalEntity.getInDatetime(), "yyyy-MM-dd HH:mm:ss"));
            param.put("admission_date_time", inDatetime + ":00");
            //param.put("adm_ward_date_time", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            param.put("adm_ward_date_time", inDatetime + ":00");
            //param.put("cost_emp_no", userMapper.queryEmpNoById(doctorPersonId, "doctor"));
            param.put("cost_emp_no", patientInHospitalMapper.queryUserIdByPersonId(doctorPersonId));
            param.put("diagnosis", res != null ? res.get("DIAG_NAME") : "");
            param.put("diagnosis_icd", res != null ? res.get("DIAG_ICD") : "");
            //param.put("task_nurse_no", userMapper.queryEmpNoById(nurseId, "nurse"));
            param.put("task_nurse_no", patientInHospitalMapper.queryUserIdByPersonId(nurseId));
            param.put("operationID", ConstantEnum.HIS_CIRCULATION_10041.getKey());
            param.put("operating_date", "");
            param.put("operation_name", "");
            param.put("patient_condition", "");
            param.put("cell", "");
            param.put("operation_code", "");
            requestMap.put("request", param);
            map.put("c_request", requestMap);
            map.put("operationID", ConstantEnum.HIS_CIRCULATION_10041.getKey());
            log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
            System.out.println(JSON.toJSONString(map));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, map);
            if (jsonObject.isEmpty()) {
                return ResultGenerator.genFailedResult("患者入院失败");
            }
            log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    //return ResultGenerator.genFailedResult("HIS接口调用失败");
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
            String bedLabel = circulationLogMapper.queryBedLabel(wardDeptId, bedNo);

        //2.保存病人信息
            patientInHospitalEntity.setResponsibleDoctorPersonId(doctorPersonId);
            patientInHospitalEntity.setBedNo(bedNo);
            patientInHospitalEntity.setInDatetime(DateUtil.dateToTimestamp(DateUtil.stringToDate(inDatetime + ":00", "yyyy-MM-dd HH:mm:ss")));
            patientInHospitalEntity.setInpatTimes(patientInHospitalEntity.getInpatTimes());
            patientInHospitalEntity.setResponsibleNursePersonId(nurseId);
            patientInHospitalEntity.setDeptId(deptId);
            patientInHospitalEntity.setInDeptId(deptId);
            patientInHospitalEntity.setInWardDatetime(DateUtil.dateToTimestamp(DateUtil.stringToDate(inDatetime + ":00", "yyyy-MM-dd HH:mm:ss")));
            patientInHospitalEntity.setWardDeptId(wardDeptId);
            patientInHospitalMapper.updateByPrimaryKeySelective(patientInHospitalEntity);
            //设置护士信息
            circulationLogMapper.mergesaveMedicalRecordsOthers(UUIDUtil.randomString(), StateEnum.HOSPITAL_ID.getValue(), inpatNum, nurseId);

            //4.增加入院完成日志(待入院信息)
            CirculationLogEntity circulationLogEntity = circulationLogMapper.queryCirculationLogById(circulationLogId);
            if (null == circulationLogEntity) {
                return ResultGenerator.genOkResult();
            }
            circulationLogEntity.setInNurseId(nurseId);
            circulationLogEntity.setInWardDeptId(wardDeptId);
            circulationLogEntity.setInDoctorPersonId(doctorPersonId);
            circulationLogEntity.setInBedNo(bedNo);
            circulationLogEntity.setInBedLabel(bedLabel);
            //circulationLogEntity.setInDatetime(DateUtil.stringToDate(inDatetime + ":00", "yyyy-MM-dd HH:mm:ss"));
            circulationLogEntity.setInDeptId(deptId);
            //circulationLogEntity.setEditFlag("1");
            circulationLogEntity.setStatus(1);
            circulationLogEntity.setOperator(userId);
            //更新入院状态(待入院信息)
            circulationLogMapper.updateByPrimaryKeySelective(circulationLogEntity);

            //增加入院完成日志
            CirculationLogEntity inHosEntity = new CirculationLogEntity();
            inHosEntity.initAdd();
            inHosEntity.setStatus(1);
            inHosEntity.setCirculationLogId(UUIDUtil.randomString());
            inHosEntity.setCirculationModelType(CirculationModelEnum.FINISH_IN_HOSP.getCode());
            inHosEntity.setCirculationOperateType(CirculationTypeEnum.IN_HOSP.getCode());
            inHosEntity.setHealthNum(patientInHospitalEntity.getHealthNum());
            inHosEntity.setInBedNo(bedNo);
            inHosEntity.setInBedLabel(bedLabel);
            inHosEntity.setInDatetime(DateUtil.stringToDate(inDatetime + ":00", "yyyy-MM-dd HH:mm:ss"));
            inHosEntity.setInDeptId(deptId);
            inHosEntity.setInDoctorPersonId(doctorPersonId);
            inHosEntity.setInNurseId(nurseId);
            inHosEntity.setInpatNum(inpatNum);
            inHosEntity.setInWardDeptId(wardDeptId);
            inHosEntity.setPatTypeId(patientInHospitalEntity.getPatTypeId());
            inHosEntity.setSerialNo(null == circulationLogEntity.getSerialNo() ? 1 : circulationLogEntity.getSerialNo() + 1);
            inHosEntity.setSourceType(Constant.SELF);
            inHosEntity.setBatchNo(circulationLogEntity.getBatchNo());
            inHosEntity.setOperator(userId);
            circulationLogMapper.insert(inHosEntity);

            //更新床号
            circulationLogMapper.updateBedNoStatus(bedNo, wardDeptId, "1");


            //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
            List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(circulationLogId);
            //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
            if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds,inHosEntity.getCirculationLogId());
            }

            //更新
            params.put("newCirculationLogId",inHosEntity.getCirculationLogId());

            return ResultGenerator.genOkResult(params);
        //}
    }


    public Result savePatientInfoInDept(Map<String, Object> params) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String inpatNum = (String) params.get("inpatNum");
        String bedNo = (String) params.get("bedNo");
        //String deptId = (String)params.get("deptId");
        //String deptName = (String)params.get("deptName");
        String doctorPerson = (String) params.get("doctorPerson");
        String doctorPersonId = (String) params.get("doctorPersonId");
        String nurseId = (String) params.get("nurseId");
        String nurseName = (String) params.get("nurseName");
        String wardDeptId = (String) params.get("wardDeptId");
        String circulationLogId = (String) params.get("circulationLogId");
        String editFlag = (String) params.get("editFlag");
        String transferInDateTime = (String) params.get("transferInDateTime");

        if (StringUtils.isNotEmpty(editFlag) && "1".equals(editFlag)) {
            return ResultGenerator.genOkResult(params);
        } else {
            CirculationLogEntity circulationLogEntity = circulationLogMapper.queryCirculationLogById(circulationLogId);
            //List<Map<String, String>> rotatingList = circulationLogMapper.getRotatingList(inpatNum, StateEnum.INCOMPLETE.getValue(), CirculationTypeEnum.TRANSFERRED_DEPT.getCode(), CirculationModelEnum.WAIT_IN_DEPT.getCode(), null,null);//获取待转入日志
            if (circulationLogEntity == null) {
                return ResultGenerator.genFailedResult("此病人无待转入记录");
            } else {
                String deptId = circulationLogEntity.getInDeptId();
                if (StringUtils.isBlank(deptId)) {
                    return ResultGenerator.genFailedResult("数据异常,日志中无转入科室");
                }
                Map<String, String> patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, circulationLogId);
                //his接口
                //调用转科his接口
                Map<String, Object> param = new HashMap<>();
                //病人编码 住院号
                param.put("p_patient_id", patient.get("medicalNum"));
                //就诊次数 住院号-后的值
                param.put("p_visit_id", patient.get("inpatTimes"));
                //床号
                param.put("p_bed_no", bedNo);
                //科室代码
                param.put("p_dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(circulationLogEntity.getInDeptId()));
                //病区代码
                param.put("p_ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(circulationLogEntity.getInWardDeptId()));
                //入院时间
                param.put("p_in_date", patient.get("inTime"));
                //转入时间
                //param.put("p_in_dept_date", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
                param.put("p_in_dept_date", transferInDateTime+":00");
                //责任医生
                param.put("p_doctor", patientInHospitalMapper.queryUserIdByPersonId(doctorPersonId));
                //责任护士
                param.put("p_nurse", patientInHospitalMapper.queryUserIdByPersonId(nurseId));
                //入科操作码
                param.put("operationID", ConstantEnum.HIS_CIRCULATION_10032.getKey());

                System.out.println(JSON.toJSONString(param));
                JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
                if (jsonObject.isEmpty()) {
                    return ResultGenerator.genFailedResult("患者转科转入失败");
                }
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    //return ResultGenerator.genFailedResult("HIS接口调用失败");
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }

                //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                //circulationLogMapper.updateLogStatusById(circulationLogId, sdf.format(new Date()), null, StateEnum.COMPLETED.getValue());//更新日志状态
                circulationLogEntity.setInNurseId(nurseId);
                circulationLogEntity.setInDoctorPersonId(doctorPersonId);
                circulationLogEntity.setInBedNo(bedNo);
                //circulationLogEntity.setInDatetime(new Date());
                circulationLogEntity.setInDatetime(DateUtil.stringToDate(transferInDateTime+":00","yyyy-MM-dd HH:mm:ss"));
                circulationLogEntity.setEditFlag("1");
                circulationLogEntity.setOperator(userId);
                //更新入院状态
                circulationLogMapper.updateByPrimaryKeySelective(circulationLogEntity);

                circulationLogMapper.updatePatient(inpatNum, bedNo, deptId, circulationLogEntity.getInWardDeptId(), doctorPersonId, nurseId);
                //设置护士信息
                circulationLogMapper.mergesaveMedicalRecordsOthers(UUIDUtil.randomString(), StateEnum.HOSPITAL_ID.getValue(), inpatNum, nurseId);
                //更新床号
                circulationLogMapper.updateBedNoStatus(bedNo, wardDeptId, "1");
            }
            return ResultGenerator.genOkResult(params);
        }
    }

    public String getCirculationModelTypeName(String type) {
        String typeName = "无";
        if (CirculationModelEnum.WAIT_IN_HOSP.getCode().equals(type)) {
            typeName = "新入";
        } else if (CirculationModelEnum.WAIT_IN_DEPT.getCode().equals(type)) {
            typeName = "转科-转入";
        } else if (CirculationModelEnum.WAIT_OUT_DEPT.getCode().equals(type)) {
            typeName = "转科-转出";
        } else if (CirculationModelEnum.WAIT_OUT_HOSP.getCode().equals(type)) {
            typeName = "出院";
        } else if (CirculationModelEnum.WAIT_ROTATING_BED.getCode().equals(type)) {
            typeName = "迁床";
        } else if (CirculationModelEnum.WAIT_OUT_WARD.getCode().equals(type)) {
            typeName = "手术-转出";
            //typeName = "出室";
        } else if (CirculationModelEnum.WAIT_IN_WARD.getCode().equals(type)) {
            //typeName = "手术-转入";
            typeName = "回室";
        } else if (CirculationModelEnum.WAIT_OUT_OPERATION.getCode().equals(type)) {
            //typeName = "手术室-转出";
            typeName = "出室";
        } else if (CirculationModelEnum.WAIT_IN_OPERATION.getCode().equals(type)) {
            //typeName = "手术室-转入";
            typeName = "入室";
        } else if (CirculationModelEnum.WAIT_IN_RESUSCITATION.getCode().equals(type)) {
            //typeName = "复苏室-转入";
            typeName = "入室";
        } else if (CirculationModelEnum.WAIT_OUT_RESUSCITATION.getCode().equals(type)) {
            //typeName = "复苏室-转出";
            typeName = "出室";
        }
        return typeName;

    }

    public String getCirculationModelTypeFlag(String type) {
        String typeFlag = null;
        String[] types = type.split("_");
        if (types != null && types.length == 3) {
            return types[1] + "_" + types[2];
        }
        return typeFlag;

    }

    /**
     * 病人扫腕带
     *
     * @param qrCode
     * @param wardDeptId
     * @param startDate
     * @param endDate
     * @return
     */
    public Result patientScanWristBandCode(String qrCode, String wardDeptId, String startDate, String endDate) {
        String inpatNum = taskExecuteMapper.queryInpatNumByQrcode(qrCode);
        if (StringUtils.isNotBlank(inpatNum)) {
            List<String> circulationModel = new ArrayList<String>(Arrays.asList(CirculationModelEnum.WAIT_IN_HOSP.getCode(),
                    CirculationModelEnum.WAIT_IN_DEPT.getCode(),
                    CirculationModelEnum.WAIT_OUT_DEPT.getCode(),
                    CirculationModelEnum.WAIT_OUT_HOSP.getCode(),
                    CirculationModelEnum.WAIT_ROTATING_BED.getCode(),
                    CirculationModelEnum.WAIT_OUT_WARD.getCode(),
                    CirculationModelEnum.WAIT_IN_WARD.getCode(),
                    CirculationModelEnum.WAIT_OUT_OPERATION.getCode(),
                    CirculationModelEnum.WAIT_IN_OPERATION.getCode(),
                    CirculationModelEnum.WAIT_IN_RESUSCITATION.getCode(),
                    CirculationModelEnum.WAIT_OUT_RESUSCITATION.getCode()));
            //用来对查询结果进行筛选
            String screeningCondition = null;
            String wardDeptName = null;
            String deptArea = null;

            if (StringUtils.isNotBlank(wardDeptId)) {
                //MavEmrCoreDictDTO dictDTO = dictMapper.getByValueId(wardDeptId);
                SysDeptDictEntity sysDeptDictEntity = sysDeptDictMapper.selectByPrimaryKey(wardDeptId);
                //if (null != dictDTO) {
                if (null != sysDeptDictEntity) {
                    String deptName = sysDeptDictEntity.getDeptName();
                    deptArea = sysDeptDictEntity.getDeptArea();

                    if (deptName.contains("手术室护理单元")) {
                        //手术科室，只查询手术室转入、转出相关信息
                        circulationModel = circulationModel.stream().filter(ct -> ct.indexOf("_operation") > 0)
                                .collect(Collectors.toList());
                        wardDeptId = "";
                        screeningCondition = "operation";
                    } else if (deptName.contains("麻醉护理单元")) {
                        //复苏科室，只查询复苏室转入、转出相关信息
                        circulationModel = circulationModel.stream().filter(ct -> ct.indexOf("_resuscitation") > 0)
                                .collect(Collectors.toList());
                        wardDeptId = "";
                        screeningCondition = "resuscitation";
                    } else {
                        //普通科室，查询不包含手术、复苏科室的信息
                        List<String> operations = circulationModel.stream().filter(ct -> ct.indexOf("_operation") > 0).collect(Collectors.toList());
                        List<String> resuscitations = circulationModel.stream().filter(ct -> ct.indexOf("_resuscitation") > 0).collect(Collectors.toList());
                        circulationModel.removeAll(operations);
                        circulationModel.removeAll(resuscitations);
                    }
                }
            }
            List<String> types = circulationLogMapper.getModelTypesInInpatNum(circulationModel, endDate, startDate, wardDeptId, inpatNum);
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            for (String type : types) {
                Map map = new HashMap();
                List<Map<String, String>> result = circulationLogMapper.getPatientListByInpatNum(endDate, startDate, type, wardDeptId, deptArea, inpatNum);

                for (Map<String, String> item : result) {
                    if (StringUtils.isBlank(item.get("wardName"))) {
                        continue;
                    }
                    int ind = item.get("wardName").indexOf("护理单元");
                    if (ind > 0) {
                        item.put("wardName", item.get("wardName").substring(0, ind));
                    }
                }
                if (type != null) {
                    map.put("type", type);
                } else {
                    map.put("type", "无");
                }
                map.put("patients", result);
                map.put("typeName", getCirculationModelTypeName(type));
                map.put("typeFlag", getCirculationModelTypeFlag(type));
                resultList.add(map);
            }
            //过滤手术待转出数据
            if (CollectionUtils.isNotEmpty(resultList)) {
                String prevTime = DateUtil.dateToString(DateUtil.getDateBefore(new Date(),0),"yyyy-MM-dd");
                for (Map<String, Object> map : resultList) {
                    if (CirculationModelEnum.WAIT_OUT_WARD.getCode().equals((String) map.get("type"))) {
                        List<Map<String, String>> patientsList = (List<Map<String, String>>) map.get("patients");

                        List<Map<String, String>> patientsNewList = new ArrayList<Map<String, String>>();
                        if (CollectionUtils.isNotEmpty(patientsList)) {
                            for (Map<String, String> pat : patientsList) {
                                CirculationLogDTO circulationLogEntity = circulationLogMapper.queryDtoCirculationLogById(pat.get("circulationLogId"));
                                Map<String, String> operation = circulationLogMapper.queryPatientOperationByInpatorderdataId(circulationLogEntity.getInpatorderdataId());
                                String operationTime = circulationLogMapper.queryOperationTime(circulationLogEntity.getInpatorderdataId());
                                if(StringUtils.isNotBlank(operationTime) && prevTime.compareTo(operationTime.substring(0,10))<=0){
                                    String visitId = pat.get("inpatNum").split("-")[1];
                                    //his对接
                                    Map<String, Object> param = new HashMap<>();
                                    //病人编码 住院号
                                    param.put("p_patient_id", pat.get("medicalNum"));
                                    //就诊次数 住院号-后的值
                                    param.put("p_visit_id", visitId);
                                    //排序字段及方向
                                    param.put("p_sort", "");
                                    //当前页-默认第一页
                                    param.put("p_curPage", "1");
                                    //每页行数-默认每页10行
                                    param.put("p_pageSize", "10");
                                    //手术操作码
                                    param.put("operationID", ConstantEnum.HIS_CIRCULATION_10046.getKey());
                                    System.out.println(JSON.toJSONString(param));

                                    JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
                                    if (jsonObject.isEmpty()) {
                                    }
                                    Integer resInt = Integer.valueOf((String) jsonObject.get("p_totalRecords"));
                                    if (resInt < 0) {
                                    }
                                    if (jsonObject.getString("data") != null) {
                                        List<Map> list = JSONArray.parseArray(jsonObject.getString("data"), Map.class);
                                        if (list != null && list.size() > 0) {
                                            for (Map oMap : list) {
                                                if (CommonUtils.isNotEmpty((String) oMap.get("OPERATING_ROOM_NO")) && CommonUtils.isNotEmpty((String) oMap.get("ARRANGE_DATE_TIME"))) {
                                                    if ((oMap.get("OPERATION")).equals(operation.get("operationName")) && operationTime.equals(oMap.get("SCHEDULED_DATE_TIME"))) {
                                                        patientsNewList.add(pat);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        map.put("patients", patientsNewList);
                    }
                }
            }
            List<Map<String, Object>> lastResultList = new ArrayList<Map<String, Object>>();
            if (CollectionUtils.isNotEmpty(resultList)) {
                for (Map<String, Object> map : resultList) {
                    List<Map<String, String>> patients = (List<Map<String, String>>) map.get("patients");
                    if (CollectionUtils.isNotEmpty(patients)) {
                        lastResultList.add(map);
                    }
                }
            }

            if (lastResultList == null || lastResultList.size() == 0) {
                return ResultGenerator.genFailedResult("此病人没有对应流转信息!");
            }
            return ResultGenerator.genOkResult(lastResultList);
        } else {
            return ResultGenerator.genFailedResult("无此病人信息!");
        }
    }

    /**
     * 病人扫床头码
     *
     * @param qrCode
     * @param circulationlLogId
     * @return
     */
    public Result patientScanBedCode(String qrCode, String circulationlLogId) {
        CirculationLogEntity circulationLogEntity = circulationLogMapper.queryDtoCirculationLogById(circulationlLogId);
        String[] bedCards = qrCode.split("_");
        if (circulationLogEntity != null) {
            if (bedCards != null && bedCards.length == 2) {
                //根据bedCards[0]查询
                if (StringUtils.isNotEmpty(bedCards[0]) && StringUtils.isNotEmpty(bedCards[1]) &&
                        StringUtils.isNotEmpty(circulationLogEntity.getInWardDeptId()) && StringUtils.isNotEmpty(circulationLogEntity.getInBedNo()) &&
                        bedCards[0].equals(circulationLogEntity.getInWardDeptId()) && bedCards[1].equals(circulationLogEntity.getInBedNo())) {
                    return ResultGenerator.genOkResult("已核对");
                } else {
                    return ResultGenerator.genFailedResult("核对床位信息失败!");
                }
            } else {
                return ResultGenerator.genFailedResult("此二维码不是床头牌!");
            }
        } else {
            return ResultGenerator.genFailedResult("此人有效的无迁床信息!");
        }
    }


    public Result getCirculationType() {
        List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("typeName", "全部");
        map.put("typeId", "-1");
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "入院");
        map.put("typeId", CirculationModelEnum.FINISH_IN_HOSP.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "取消入院");
        map.put("typeId", CirculationModelEnum.CANCLE_IN_HOSP.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "转入");
        map.put("typeId", CirculationModelEnum.FINISH_IN_DEPT.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "取消转入");
        map.put("typeId", CirculationModelEnum.CANCLE_IN_DEPT.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "出院");
        map.put("typeId", CirculationModelEnum.FINISH_OUT_HOSP.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "取消出院");
        map.put("typeId", CirculationModelEnum.CANCLE_OUT_HOSP.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "迁床");
        map.put("typeId", CirculationModelEnum.FINISH_ROTATING_BED.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "转出");
        map.put("typeId", CirculationModelEnum.FINISH_OUT_DEPT.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "取消转出");
        map.put("typeId", CirculationModelEnum.CANCLE_OUT_DEPT.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "出室");
        //map.put("typeId","finish_out_ward,finish_out_operation,finish_out_resuscitation");
        map.put("typeId", CirculationModelEnum.FINISH_OUT_WARD.getCode() + "," + CirculationModelEnum.FINISH_OUT_OPERATION.getCode() + "," + CirculationModelEnum.FINISH_OUT_RESUSCITATION.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "回室");
        map.put("typeId", CirculationModelEnum.FINISH_IN_WARD.getCode());
        resultList.add(map);
        map = new HashMap<String, String>();
        map.put("typeName", "入室");
        map.put("typeId", CirculationModelEnum.FINISH_IN_OPERATION.getCode() + "," + CirculationModelEnum.FINISH_IN_RESUSCITATION.getCode());
        resultList.add(map);
        return ResultGenerator.genOkResult(resultList);
    }


    public Result queryCirculationLogList(Map<String, String> params) {
        String type = params.get("type");
        String inpatNum = params.get("inpatNum");
        String pageNum = params.get("page");
        String pageSize = params.get("pageSize");
        List<String> circulationTypeList = new ArrayList<String>();
        List<String> inpatNums = new ArrayList<String>();
        if (StringUtils.isNotEmpty(type)) {
            if ("-1".equals(type)) {
                circulationTypeList = new ArrayList<String>(Arrays.asList(
                        CirculationModelEnum.FINISH_IN_HOSP.getCode(),
                        CirculationModelEnum.CANCLE_IN_HOSP.getCode(),
                        CirculationModelEnum.FINISH_IN_DEPT.getCode(),
                        CirculationModelEnum.CANCLE_IN_DEPT.getCode(),
                        CirculationModelEnum.FINISH_OUT_DEPT.getCode(),
                        CirculationModelEnum.CANCLE_OUT_DEPT.getCode(),
                        CirculationModelEnum.FINISH_OUT_HOSP.getCode(),
                        CirculationModelEnum.CANCLE_OUT_HOSP.getCode(),
                        CirculationModelEnum.FINISH_ROTATING_BED.getCode(),
                        CirculationModelEnum.FINISH_OUT_WARD.getCode(),
                        CirculationModelEnum.FINISH_IN_WARD.getCode(),
                        CirculationModelEnum.FINISH_OUT_OPERATION.getCode(),
                        CirculationModelEnum.FINISH_IN_OPERATION.getCode(),
                        CirculationModelEnum.FINISH_IN_RESUSCITATION.getCode(),
                        CirculationModelEnum.FINISH_OUT_RESUSCITATION.getCode()));
            } else {
                circulationTypeList = new ArrayList<String>(Arrays.asList(type.split(",")));
            }
        }

        if (StringUtils.isNotEmpty(inpatNum)) {
            inpatNums = new ArrayList<String>(Arrays.asList(inpatNum.split(",")));
        } else {
            return ResultGenerator.genOkResult(null);
        }
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<CirculationLogsDTO> circulationLogList = circulationLogMapper.queryCirculationLogList(inpatNums, circulationTypeList, params.get("startDate"), params.get("endDate"));
        if (CollectionUtils.isNotEmpty(circulationLogList)) {
            for (CirculationLogsDTO circulationLogsDTO : circulationLogList) {
                Map<String, String> patientInfo = new HashMap<String, String>();
                patientInfo.put("ageYear", circulationLogsDTO.getAgeYear());
                patientInfo.put("ageMonth", circulationLogsDTO.getAgeMonth());
                patientInfo.put("ageDay", circulationLogsDTO.getAgeDay());
                patientInfo.put("ageHour", circulationLogsDTO.getAgeHour());
                patientInfo.put("ageMinute", circulationLogsDTO.getAgeMinute());
                getPatientAge(patientInfo);
                circulationLogsDTO.setAge(patientInfo.get("age"));
                String circulationModeType = circulationLogsDTO.getCirculationModelType();
                if (CirculationModelEnum.FINISH_OUT_OPERATION.getCode().equals(circulationModeType) || CirculationModelEnum.FINISH_IN_OPERATION.getCode().equals(circulationModeType)) {
                    if ("01".equals(circulationLogsDTO.getDeptArea())) {
                        //城中
                        circulationLogsDTO.setWardDeptName("手术室护理单元(城中)");
                    } else if ("02".equals(circulationLogsDTO.getDeptArea())) {
                        //阳湖
                        circulationLogsDTO.setWardDeptName("手术室护理单元(阳湖)");
                    }
                    if (StringUtils.isNotEmpty(circulationLogsDTO.getRemark())) {
                        Map<String, String> remarkMap = JSONObject.parseObject(circulationLogsDTO.getRemark(), Map.class);
                        circulationLogsDTO.setBedNo(remarkMap.get("OPERATING_ROOM_NO"));
                    }

                }
                if (CirculationModelEnum.FINISH_IN_RESUSCITATION.getCode().equals(circulationModeType) || CirculationModelEnum.FINISH_OUT_RESUSCITATION.getCode().equals(circulationModeType)) {
                    if ("01".equals(circulationLogsDTO.getDeptArea())) {
                        //城中
                        circulationLogsDTO.setWardDeptName("麻醉护理单元(城中)");
                    } else if ("02".equals(circulationLogsDTO.getDeptArea())) {
                        //阳湖
                        circulationLogsDTO.setWardDeptName("麻醉护理单元(阳湖)");
                    }
                    if (StringUtils.isNotEmpty(circulationLogsDTO.getRemark())) {
                        Map<String, String> remarkMap = JSONObject.parseObject(circulationLogsDTO.getRemark(), Map.class);
                        circulationLogsDTO.setBedNo(remarkMap.get("OPERATING_ROOM_NO"));
                    }
                }

            }
        }

        PageInfo<CirculationLogsDTO> pageInfo = new PageInfo<CirculationLogsDTO>(circulationLogList);

        return ResultGenerator.genOkResult(pageInfo);
    }

    private void getPatientAge(Map<String, String> patientInfo) {
        Integer ageYear = patientInfo.get("ageYear") == null ? 0 : Integer.parseInt(patientInfo.get("ageYear"));
        Integer ageMonth = patientInfo.get("ageMonth") == null ? 0 : Integer.parseInt(patientInfo.get("ageMonth"));
        Integer ageDay = patientInfo.get("ageDay") == null ? 0 : Integer.parseInt(patientInfo.get("ageDay"));
        Integer ageHour = patientInfo.get("ageHour") == null ? 0 : Integer.parseInt(patientInfo.get("ageHour"));
        Integer ageMinute = patientInfo.get("ageMinute") == null ? 0 : Integer.parseInt(patientInfo.get("ageMinute"));
        StringBuffer ageStr = new StringBuffer();
        if (ageYear != 0) {
            ageStr.append(ageYear + "岁");
        }
        if (ageMonth != 0) {
            ageStr.append(ageMonth + "月");
        }
        if (ageDay != 0) {
            ageStr.append(ageDay + "天");
        }
        if (ageHour != 0) {
            if (ageDay < 29) {              //28天以上不需要小时
                ageStr.append(ageHour + "小时");
            }
        }
        if (ageMinute != 0) {
            ageStr.append(ageMinute + "分钟");
        }
        if (ageStr.length() == 0) {
            ageStr.append(ageHour + "小时");
            ageStr.append(ageMinute + "分钟");
        }
        patientInfo.put("age", ageStr.toString());
    }


    public Result getPatientInfoTemp(String inpatNum, String circulationlLogId) {
        Map<String, String> map = circulationLogMapper.queryPatientCirculationLogById(circulationlLogId);
        if (map != null) {
            map.put("inpatNum", inpatNum);
            //if ("0".equals(map.get("status")) && ("wait_in_hosp".equals(map.get("circulationModelType"))|| "wait_in_dept".equals(map.get("circulationModelType")))) {
            if ("0".equals(String.valueOf(map.get("status"))) && ("wait_in_hosp".equals(map.get("circulationModelType"))|| "wait_in_dept".equals(map.get("circulationModelType")))) {
                map.put("inDatetime", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
            }
        }
        return ResultGenerator.genOkResult(map);
    }

    /**
     * 根据科室id查询所有科室所对应的病区
     *
     * @param deptId
     * @return
     */
    public Result queryWardDeptByDeptId(String deptId,String id,String keyWords) {
        return ResultGenerator.genOkResult(circulationLogMapper.queryWardDeptByDeptId(deptId,id,keyWords));
    }

    /**
     * 根据住院号获取入院评估单
     *
     * @param inpatNum
     * @return
     */
    public Result queryPatientInHospAssessmentSheet(String inpatNum) {
        //根据住院号获取已入院对应的文书Id
        List<CommonTaskCirculationDTO> list = circulationLogMapper.queryCommonTaskCirculationByInpatNum(inpatNum);
        List<Map<String, Object>> emrFileList = new CopyOnWriteArrayList<Map<String, Object>>();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, String> patient = patientInHospitalMapper.getPatientInfoNurse(inpatNum, null, null);
        if (patient != null) {
            getPatientAge(patient);
            if (org.apache.commons.lang3.StringUtils.isBlank(patient.get("inBedNo"))) {
                patient.put("inBedNo", "");
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(patient.get("outBedNo"))) {
                patient.put("outBedNo", "");
            }


            String circulationLogId = null;
            if (CollectionUtils.isNotEmpty(list)) {
                resultMap.put("executeDatetimeStr", list.get(0).getExecuteDatetimeStr());
                resultMap.put("executeUserName", list.get(0).getExecuteUserName());
                circulationLogId = list.get(0).getCirculationlLogId();
            }

            List<CirculationTemplateDTO> ctList = circulationTemplateMapper.queryTampList("admission_ssessment", inpatNum, circulationLogId);
            for (CirculationTemplateDTO circulationTemplateDTO : ctList) {
                if (StringUtils.isNotBlank(circulationTemplateDTO.getEmrFileId())) {
                    EmrFile emrFile = new EmrFile();
                    //EmrFile fileIndex = nurseFileIndexService.getFileIndex(info.getEmrFileId());
                    List<EmrFileData> lists = getEmrFileData(circulationTemplateDTO.getEmrFileId(), null);
                    emrFile.setTplName(circulationTemplateDTO.getTplName());
                    //emrFileList.add(fileIndex);
                    List<EmrFileData> topList = buildTreeData(lists, null);
                    emrFile.setEmrFileDataList(topList);
                    circulationTemplateDTO.setEmrFile(emrFile);
                } else {
                    EmrFile emrFile = new EmrFile();
                    emrFile.setEmrFileDataList(new ArrayList<EmrFileData>());
                    circulationTemplateDTO.setEmrFile(emrFile);
                }
            }

            resultMap.putAll(patient);
            resultMap.put("emrFileList", ctList);

        }

        return ResultGenerator.genOkResult(resultMap);
    }

    public Result queryPatientPayOff(String inpatNum) {
        String payOff = null;
        String url = cost;
        Map<String, Object> param = new HashMap<>();
        param.put("as_patientId", inpatNum.replace("-1", ""));
        param.put("operationID", "10001");
        param.put("al_visitId", "1");
        param.put("al_doctor_type", "");

        CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
                HttpClientUtil.sendPost(url, param)).thenApply(x -> x.toString());
        try {
            JSONObject jsonObject = JSON.parseObject(ordedCustomerFuture.get());
            if (jsonObject.getString("data") != null) {
                Map cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                if (cost.get("CHARGE_TYPE").toString().contains("自费")) {
                    payOff = "自费";
                } else {
                    payOff = cost.get("CHARGE_TYPE").toString();
                }
            }
        } catch (Exception e) {
            log.error("查询费用明细失败", e);
        }
        return ResultGenerator.genOkResult(payOff);

    }

    public List<EmrFileData> buildTreeData(List<EmrFileData> list, String parentFileIndexDataId) {
        List<EmrFileData> topList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            EmrFileData node = list.get(i);
            node.setEmrFileDataList(new ArrayList<>());
            if (node.getFileIndexDataEntity().getParentFileIndexDataId() == null
                    || node.getFileIndexDataEntity().getParentFileIndexDataId().equals(parentFileIndexDataId)) {
                node.setPath("");
                topList.add(node);
                continue;
            }
            for (int j = 0; j < i; j++) {
                EmrFileData parent = list.get(j);
                if (parent.getFileIndexDataEntity().getFileIndexDataId().equals(node.getFileIndexDataEntity().getParentFileIndexDataId())) {
                    node.setPath(parent.getPath() + "," + parent.getFileIndexDataEntity().getFileIndexDataId());
                    parent.getEmrFileDataList().add(node);
                    break;
                }
            }
        }
        return topList;
    }

    /**
     * 查询病历数据列表
     *
     * @param emrFileId             病历ID
     * @param parentFileIndexDataId 父级数据ID 可以为null
     * @return
     */
    public List<EmrFileData> getEmrFileData(String emrFileId, String parentFileIndexDataId) {
        long t1 = System.currentTimeMillis();
        //引用病历模板
        List<Map<String, Object>> list = ordersFileIndexMapper.getAllFileIndexDataEntity(emrFileId, parentFileIndexDataId, "0");

        long t2 = System.currentTimeMillis();
        List<EmrFileData> emrFileDataList = convertData(list);
      /*  emrFileDataList.stream().forEach(emrFileData -> {
            Element element = emrFileData.getElement();
            // 补充全部勾选项
            if (element.getElementPropertyFormat() != null && element.getElementPropertyFormat().indexOf("\"formatValue\":\"2\"") > -1) {
                element.setSelections(ordersFileIndexMapper.getAllSelections(element.getId()));
            }
        });*/
        return emrFileDataList;
    }

    private List<EmrFileData> convertData(List<Map<String, Object>> list) {
        return list.parallelStream().map(map -> {
            EmrFileData data = new EmrFileData();
            OrdersFileIndexDataEntity dataEntity = new OrdersFileIndexDataEntity();
            dataEntity.setFileIndexDataId((String) map.get("FILE_INDEX_DATA_ID"));
            /*try {
                if (map.get("GMT_CREATE") instanceof TIMESTAMP)
                    dataEntity.setCreateTime(((TIMESTAMP) map.get("GMT_CREATE")).timestampValue());
                else
                    dataEntity.setCreateTime((Date) map.get("GMT_CREATE"));
            } catch (SQLException e) {
                //logger.error("转换对象出错。", e);
            }*/
            /*try {
                if (map.get("GMT_MODIFY") instanceof TIMESTAMP)
                    dataEntity.setModifyTime(((TIMESTAMP) map.get("GMT_MODIFY")).timestampValue());
                else
                    dataEntity.setModifyTime((Date) map.get("GMT_MODIFY"));
            } catch (SQLException e) {
                //logger.error("转换对象出错。", e);
            }*/
            dataEntity.setSortId((map.get("SORT_ID")) == null ? 0 : ((Number) map.get("SORT_ID")).intValue());
            dataEntity.setElementId((String) map.get("ELEMENT_ID"));
            dataEntity.setParentElementId((String) map.get("PARENT_ELEMENT_ID"));
            dataEntity.setQuoteDatasetId((String) map.get("QUOTE_DATASET_ID"));
            dataEntity.setQuoteElementId((String) map.get("QUOTE_ELEMENT_ID"));
            dataEntity.setDataCode((String) map.get("DATA_CODE"));
            dataEntity.setParentFileIndexDataId((String) map.get("PARENT_FILE_INDEX_DATA_ID"));
            dataEntity.setBaseTplDetailId((String) map.get("BASE_TPL_DETAIL_ID"));
            dataEntity.setQuoteTplDetailId((String) map.get("QUOTE_TPL_DETAIL_ID"));
            String dataValue = "";
            if (map.get("DATA_VALUE_STR") != null) {
                dataValue = (String) map.get("DATA_VALUE_STR");
            } else {
                try {
                    if (map.get("DATA_VALUE") != null) {
                        if (map.get("DATA_VALUE") instanceof Clob) {
                            Clob clob = (Clob) map.get("DATA_VALUE");
                            BufferedReader reader = new BufferedReader(clob.getCharacterStream());
                            dataValue = FileCopyUtils.copyToString(reader);
                        } else
                            dataValue = (String) map.get("DATA_VALUE");
                    }
                } catch (SQLException | IOException e) {
                    //logger.error("转换对象出错。", e);
                }
            }
            dataEntity.setDataValue(dataValue);
            dataEntity.setPrintIdentification((String) map.get("PRINT_IDENTIFICATION"));
            dataEntity.setShowIdentification((String) map.get("SHOW_IDENTIFICATION"));
            dataEntity.setDeleteIdentification((String) map.get("DELETE_IDENTIFICATION"));
            dataEntity.setElementProperty((String) map.get("ELEMENT_PROPERTY"));
            dataEntity.setMedicalId((String) map.get("MEDICAL_ID"));
            dataEntity.setUnit((String) map.get("UNIT"));
            data.setNeedChanged(map.get("NEED_CHANGED") == null ? "1" : map.get("NEED_CHANGED").toString());
            data.setFileIndexDataEntity(dataEntity);
            data.setTplDetailId((String) map.get("TPL_DETAIL_ID"));
            // 补充权限调用属性
            if (map.get("TPL_DETAIL_ROLE_ID") != null) {
                EmrTemplateDetailRoleEntity roleEntity = new EmrTemplateDetailRoleEntity();
                roleEntity.setEditRoleType((String) map.get("EDIT_ROLE_TYPE"));
                roleEntity.setEditRoleId((String) map.get("EDIT_ROLE_ID"));
                roleEntity.setEditDeptId((String) map.get("EDIT_DEPT_ID"));
                roleEntity.setShowRoleType((String) map.get("SHOW_ROLE_TYPE"));
                roleEntity.setShowRoleId((String) map.get("SHOW_ROLE_ID"));
                roleEntity.setShowDeptId((String) map.get("SHOW_DEPT_ID"));
                roleEntity.setPrintRoleType((String) map.get("PRINT_ROLE_TYPE"));
                roleEntity.setPrintRoleId((String) map.get("PRINT_ROLE_ID"));
                roleEntity.setPrintDeptId((String) map.get("PRINT_DEPT_ID"));
                roleEntity.setRefState((String) map.get("REF_STATE"));
                roleEntity.setRefRoleType((String) map.get("REF_ROLE_TYPE"));
                roleEntity.setRefRoleId((String) map.get("REF_ROLE_ID"));
                roleEntity.setRefDeptId((String) map.get("REF_DEPT_ID"));
                data.setRoleEntity(roleEntity);
            }
            // 补充数据元属性
            Element element = new Element();
            element.setId((String) map.get("ELEMENT_ID"));
            element.setName((String) map.get("ELEMENT_NAME"));
            element.setType((String) map.get("ELEMENT_DATA_TYPE_ID"));
            element.setMin(map.get("MIN_VALUE") == null ? null : ((Number) map.get("MIN_VALUE")).doubleValue());
            element.setMax(map.get("MAX_VALUE") == null ? null : ((Number) map.get("MAX_VALUE")).doubleValue());
            element.setUnit(map.get("ELEMENT_UNIT") == null ? null : map.get("ELEMENT_UNIT").toString());
            element.setVarCode((String) map.get("VAR_CODE"));
            element.setMedicalId(dataEntity.getMedicalId());
            element.setFormat((String) map.get("ELEMENT_PROPERTY_FORMAT"));
            element.setElementPropertyFormat((String) map.get("ELEMENT_PROPERTY_FORMAT"));
            element.setIsPreDiag(map.get("IS_PRE_DIAG") == null ? null : map.get("IS_PRE_DIAG").toString());
            data.setElement(element);

            data.setEmrFileDataList(new ArrayList<>());
            return data;
        }).collect(Collectors.toList());
    }

    public Result queryEvaluationTime(Map<String, String> params) {
        String inpatNum = params.get("inpatNum");
        String startDate = params.get("startDate");
        String endDate = params.get("endDate");
        List<CommonTaskCirculationDTO> list = circulationLogMapper.queryEvaluationTime(inpatNum, startDate, endDate);
        return ResultGenerator.genOkResult(list);
    }

    public Result queryDailyAssessmentSheet(String modelName, String inpatNum, String circulationlLogId) {
        List<CirculationTemplateDTO> list = circulationTemplateMapper.queryTampList(modelName, inpatNum, circulationlLogId);
        //int count=0;
        if (CollectionUtils.isNotEmpty(list)) {
            for (CirculationTemplateDTO circulationTemplateDTO : list) {
                if (StringUtils.isNotBlank(circulationTemplateDTO.getEmrFileId())) {
                    circulationTemplateDTO.setExceptionFlag("异常");
                    EmrFile emrFile = new EmrFile();
                    //EmrFile fileIndex = nurseFileIndexService.getFileIndex(info.getEmrFileId());
                    List<EmrFileData> lists = getEmrFileData(circulationTemplateDTO.getEmrFileId(), null);
                    //emrFileList.add(fileIndex);
                    List<EmrFileData> topList = buildTreeData(lists, null);
                    emrFile.setEmrFileDataList(topList);
                    circulationTemplateDTO.setEmrFile(emrFile);
                } else {
                    EmrFile emrFile = new EmrFile();
                    emrFile.setEmrFileDataList(new ArrayList<EmrFileData>());
                    circulationTemplateDTO.setEmrFile(emrFile);
                    circulationTemplateDTO.setExceptionFlag("无明显异常");
                }
            }
        }
        return ResultGenerator.genOkResult(list);
    }


    @Override
    public Result outDiagnosis(String keyWord, Integer page, Integer pageSize,String diagId) {
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = patientInHospitalMapper.queryDiagnosisList(diagId,keyWord);
        if(CollectionUtils.isNotEmpty(list)){
            list.parallelStream().forEach(x->{
                x.remove("id");
                x.remove("name");
                x.remove("wbCode");
                x.remove("diagIcd");
                x.remove("pyCode");
            });
        }
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);

        //费别 注释的是正式参数与返回
        /*String url = circulationUrl2;
        Map<String, Object> param = new HashMap<>();
        param.put("p_dis_name_part", keyWord);
        param.put("p_dis_icd_part", "");
        param.put("p_dis_py", "");
        param.put("p_dis_wb", "");
        param.put("p_sort", "dis_id");
        param.put("p_curPage", page);
        param.put("p_pageSize", pageSize);
        param.put("operationID", "10043");

        CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
                HttpClientUtil.sendPost(url, param)).thenApply(x -> x.toString());
        try {
            JSONObject jsonObject = JSON.parseObject(ordedCustomerFuture.get());

            PageInfo pageInfo = new PageInfo(jsonObject.getJSONArray("data"));
            pageInfo.setTotal(jsonObject.getInteger("p_totalRecords"));
            return ResultGenerator.genOkResult(pageInfo);
        } catch (Exception e) {
            log.error("查询费用明细失败", e);
        }*/

        //return ResultGenerator.genOkResult();
    }

    /**
     * 获取年龄
     * @param patientInHospitalEntity
     * @return
     */
    public int getPatientAge(PatientInHospitalEntity patientInHospitalEntity){
        Integer ageYear = patientInHospitalEntity.getAgeYear();
        Integer ageMonth = patientInHospitalEntity.getAgeMonth();
        Integer ageDay = patientInHospitalEntity.getAgeDay();
        Integer ageHour = patientInHospitalEntity.getAgeHour();
        Integer ageMinute = patientInHospitalEntity.getAgeMinute();
        int age = 1;
        if(ageYear!=null){
            age=ageYear;
        }else if(ageMonth!=null){
        }else if(ageDay!=null){
        }else if(ageHour!=null){
        }else if(ageMinute!=null){
        }
        return age;
    }
    public Result queryAssessmentScale(String modelName, String inpatNum, String keyWords) {
        PatientInHospitalEntity patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
        int patientAge = this.getPatientAge(patientInHospitalEntity);
        //获取评估量表
        List<NurseFormDTO> nurseForms = circulationLogMapper.getFromByCatalogId(null);
        if (CollectionUtils.isNotEmpty(nurseForms)) {
            nurseForms.stream().forEach(nurseFormEntity -> {
                EmrTemplateDTO emrTemplateDTO = circulationLogMapper.listTemplateDto(nurseFormEntity.getBasicdatavalueId());
                TableDTO vteDetail = this.getVteDetail(inpatNum, nurseFormEntity.getBasicdatavalueId(), null, null,emrTemplateDTO.getTplName().trim());
                nurseFormEntity.setVteDetail(vteDetail);
                //处理table列名
                /*EmrTemplateDTO emrTemplateDTO = circulationLogMapper.listTemplateDto(nurseFormEntity.getBasicdatavalueId());
                //获取最新的一条评估记录
                EmrFileIndexEntity emrFileIndexEntity = circulationLogMapper.findVteFileIndex(inpatNum, nurseFormEntity.getBasicdatavalueId());
                if (emrFileIndexEntity != null) {
                    StringBuffer result = new StringBuffer();
                    List<EmrTemplateDetailEntity> tplDetails = circulationLogMapper.getVteTemplateDetail(PARAM, nurseFormEntity.getBasicdatavalueId());
                    if (CollectionUtils.isNotEmpty(tplDetails)) {
                        List<Map<String, String>> detailValueList = circulationLogMapper.getVteDetail(emrFileIndexEntity.getEmrFileId(), tplDetails);
                        AtomicInteger i = new AtomicInteger(0);
                        detailValueList.forEach(detailValue -> {
                            if (StringUtils.isNotBlank(detailValue.get("DATA_VALUE"))) {
                                //map.put(detailValue.get("ELEMENT_ID"), (detailValue.get("DATA_VALUE")==null ? "" : detailValue.get("DATA_VALUE"))+(detailValue.get("UNIT")==null ? "" : detailValue.get("UNIT")));
                                if (i.get() == 0) {
                                    result.append(detailValue.get("DATA_VALUE") == null ? "" : detailValue.get("DATA_VALUE") + "分,");
                                } else {
                                    result.append(detailValue.get("DATA_VALUE") == null ? "" : detailValue.get("DATA_VALUE") + ",");
                                }
                                i.getAndIncrement();
                            }
                        });
                    }
                    if (result != null && result.length() > 0) {
                        result.deleteCharAt(result.length() - 1);
                        nurseFormEntity.setResult(result.toString());
                    }
                    //nurseFormEntity.setEmrFileId(emrFileIndexEntity.getEmrFileId());
                    nurseFormEntity.setReferenceMark(emrFileIndexEntity.getEmrFileId());
                }
                */
                if (emrTemplateDTO != null) {
                    nurseFormEntity.setTplId(emrTemplateDTO.getTplId());
                    nurseFormEntity.setTplName(emrTemplateDTO.getTplName().trim());
                }
            });
        }

        //根据评估项目新增模板数据
        List<CirculationTemplateDTO> ctList = circulationTemplateMapper.queryTampListAssessmentScale(modelName, inpatNum, null, null);
        if (CollectionUtils.isEmpty(ctList)) {
            List<CirculationTemplateDTO> circulationTemplateDTOS = circulationLogMapper.queryCirculationTemplateByModelRelation("2");
            if (CollectionUtils.isNotEmpty(circulationTemplateDTOS)) {
                circulationTemplateDTOS.stream().forEach(circulationTemplateDTO -> {
                    AtomicInteger i = new AtomicInteger(1);
                    String modelNames = circulationTemplateDTO.getModelName();
                    if (CollectionUtils.isNotEmpty(nurseForms)) {
                        nurseForms.stream().forEach(nurseFormEntity -> {
                            String tplId = nurseFormEntity.getTplId();
                            if (StringUtils.isNotBlank(tplId) && StringUtils.isNotBlank(nurseFormEntity.getTplName())) {
                                CirculationTemplateDTO circulationTemplateInfo = circulationLogMapper.queryCirculationTemplateByParentModelAndTplId(modelNames, tplId);
                                if (circulationTemplateInfo == null) {
                                    circulationTemplateInfo = new CirculationTemplateDTO();
                                    circulationTemplateInfo.setCirculationTemplateId(UUIDUtil.randomString());
                                    circulationTemplateInfo.initAdd();
                                    circulationTemplateInfo.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                                    circulationTemplateInfo.setTplId(nurseFormEntity.getTplId());
                                    circulationTemplateInfo.setTplName(nurseFormEntity.getTplName());
                                    circulationTemplateInfo.setOrderNo(i.get() + "");
                                    circulationTemplateInfo.setCirculationType("child");
                                    try {
                                        circulationTemplateInfo.setModelName(circulationTemplateDTO.getParentModel() + "_" + ChineseCharactersCode.getPinyinCode(nurseFormEntity.getTplName()).toLowerCase());
                                    } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                                        badHanyuPinyinOutputFormatCombination.printStackTrace();
                                    }
                                    circulationTemplateInfo.setParentModel(modelNames);
                                    circulationTemplateInfo.setCallFlag(circulationTemplateDTO.getCallFlag());
                                    circulationLogMapper.insertCirculationTemplate(circulationTemplateInfo);
                                    i.getAndIncrement();
                                }
                            }
                        });
                    }
                });
            }
        }
        //日常评估量表 没有circulationLogId的值
        List<CirculationTemplateDTO> list = circulationTemplateMapper.queryTampListAssessmentScale(modelName, inpatNum, null, keyWords);
        if (CollectionUtils.isNotEmpty(list)) {
            for (CirculationTemplateDTO circulationTemplateDTO : list) {
                for (NurseFormDTO nurseFormEntity : nurseForms) {
                    if (StringUtils.isNotBlank(nurseFormEntity.getTplId()) && circulationTemplateDTO.getTplId().equals(nurseFormEntity.getTplId())) {
                        String ageFrom = nurseFormEntity.getAgeFrom();
                        String ageTo = nurseFormEntity.getAgeTo();
                        if(StringUtils.isNotBlank(ageFrom) && StringUtils.isNotBlank(ageTo)){
                            if(!(patientAge>=Integer.parseInt(ageFrom) && Integer.parseInt(ageTo)>=patientAge)){
                                circulationTemplateDTO.setShowFlag(false);
                            }
                        }else if(StringUtils.isNotBlank(ageFrom)){
                            if(Integer.parseInt(ageFrom)<patientAge){
                                circulationTemplateDTO.setShowFlag(false);
                            }
                        }else if(StringUtils.isNotBlank(ageTo)){
                            if(patientAge<=Integer.parseInt(ageTo)){
                                circulationTemplateDTO.setShowFlag(false);
                            }
                        }
                        //circulationTemplateDTO.setResult(nurseFormEntity.getResult());
                        //circulationTemplateDTO.setExceptionFlag(nurseFormEntity.getReferenceMark());
                        circulationTemplateDTO.setVteDetail(nurseFormEntity.getVteDetail());
                    }
                }
            }
            list = list.stream().filter(x -> x.getShowFlag()).collect(Collectors.toList());

        }
        //根据result值进行排序
        List<CirculationTemplateDTO> collect = new ArrayList<CirculationTemplateDTO>();
        if (CollectionUtils.isNotEmpty(list)) {
            collect = list.stream().sorted(Comparator.comparing(PatientCirculationServiceImpl::comparingByResult, Comparator.nullsFirst(String::compareTo)).reversed())
                    .collect(Collectors.toList());
        }
        return ResultGenerator.genOkResult(collect);
    }


    public TableDTO getVteDetail(String inpatNum, String catalogId, String strTm, String endTm,String tplName) {
        TableDTO tableDTO = new TableDTO();
        List<TableHeader> headers = new ArrayList<>();
        //处理table列名
        List<EmrTemplateDetailEntity> tplDetails = circulationLogMapper.getVteTemplateDetail(PARAM, catalogId);
        EmrCatalogEntity emrCatalogEntity = emrCatalogMapper.selectByPrimaryKey(catalogId);
        if (tplDetails.isEmpty()) {
            tableDTO.setHeader(Collections.emptyList());
            tableDTO.setList(Collections.emptyList());
            return tableDTO;
        }
        for (EmrTemplateDetailEntity tplDetail : tplDetails) {
            String elementProperty = tplDetail.getElementProperty();
            Map<String, Object> json = JSONUtils.jsonToMap(elementProperty);
            TableHeader tableHeader = new TableHeader();
            tableHeader.setProps(tplDetail.getElementId());
            tableHeader.setTdTableNode((String) json.get("tdTableNode"));
            tableHeader.setTdTableNodeWidth((Integer) json.get("tdTableNodeWidth"));
            tableHeader.setListNum((Integer) json.get("listNum"));
            headers.add(tableHeader);
        }
        tableDTO.setHeader(headers);
        List<Map<String, Object>> list = new ArrayList<>();
        //查询所有病历
        List<EmrFileIndexEntity> fileIndexEntities = circulationLogMapper.findVteFileIndex2(inpatNum, catalogId);
        for (EmrFileIndexEntity fileIndex : fileIndexEntities) {
            Map<String, Object> map = new HashMap<>();
            String date = DateUtil.dateToString(fileIndex.getFileDatetime(), "yyyy-MM-dd HH:mm");
            map.put("emrFileId", fileIndex.getEmrFileId());
            map.put("fileDatetime", date);
            map.put("status",fileIndex.getStatus());
            map.put("emrType",emrCatalogEntity.getEmrType());
            map.put("tplName",tplName);
            List<Map<String, String>> detailValueList = circulationLogMapper.getVteDetail(fileIndex.getEmrFileId(), tplDetails);
            detailValueList.forEach(detailValue -> {
                if(org.apache.commons.lang3.StringUtils.isNotBlank(detailValue.get("DATA_VALUE"))){
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(detailValue.get("varCode")) && ( VarCodeEnum.CAPRINI_GRADE.getVarCode().equals(detailValue.get("varCode"))
                                                                                                        || VarCodeEnum.PADUA_GRADE.getVarCode().equals(detailValue.get("varCode"))
                                                                                                        || VarCodeEnum.CFALL_GRADE.getVarCode().equals(detailValue.get("varCode"))
                                                                                                        || VarCodeEnum.BRADENQ_GRADE.getVarCode().equals(detailValue.get("varCode"))
                                                                                                        || VarCodeEnum.BARTHEL_GRADE.getVarCode().equals(detailValue.get("varCode"))
                                                                                                        || VarCodeEnum.CATHETER_GRADE.getVarCode().equals(detailValue.get("varCode"))
                                                                                                        || VarCodeEnum.NUTRITIONAL_RISK_GRADE.getVarCode().equals(detailValue.get("varCode"))
                                                                                                        || VarCodeEnum.MORSE_GRADE.getVarCode().equals(detailValue.get("varCode"))
                                                                                                        || VarCodeEnum.BRADEN_GRADE.getVarCode().equals(detailValue.get("varCode")))){
                        map.put("grade", (detailValue.get("DATA_VALUE")==null ? "" : detailValue.get("DATA_VALUE"))+(detailValue.get("UNIT")==null ? "" : detailValue.get("UNIT")));
                        map.put(detailValue.get("ELEMENT_ID"), (detailValue.get("DATA_VALUE")==null ? "" : detailValue.get("DATA_VALUE"))+(detailValue.get("UNIT")==null ? "" : detailValue.get("UNIT")));
                    }else if(org.apache.commons.lang3.StringUtils.isNotBlank(detailValue.get("varCode")) && ( VarCodeEnum.VTE_ZPF.getVarCode().equals(detailValue.get("varCode"))
                                                                                                            || VarCodeEnum.NUTRITIONAL_RISK_PF.getVarCode().equals(detailValue.get("varCode")))){
                        map.put(detailValue.get("ELEMENT_ID"), (detailValue.get("DATA_VALUE")==null ? "" : detailValue.get("DATA_VALUE"))+(detailValue.get("UNIT")==null ? "" : detailValue.get("UNIT")));
                        map.put("score", (detailValue.get("DATA_VALUE")==null ? "" : detailValue.get("DATA_VALUE")));
                        map.put("colorFlag","0");
                        //设置颜色

                        if(StringUtils.isNotBlank((String)map.get("score"))){
                            int score = Integer.parseInt(String.valueOf(((String) map.get("score")).replaceAll("分","")));
                            //Morse跌倒评分
                            if (VarCodeEnum.MORSE.getName().equals(tplName)) {
                                if(score>=45){
                                    map.put("colorFlag","1");
                                }

                            } else if (VarCodeEnum.CAPRINI.getName().equals(tplName)) {
                                //Caprini评分
                                if(score>=5){
                                    map.put("colorFlag","2");
                                }else if(score>=3 && score<=4){
                                    map.put("colorFlag","3");
                                }
                            } else if (VarCodeEnum.PADUA.getName().equals(tplName)) {
                                //Padua评分
                                if(score>=4){
                                    map.put("colorFlag","2");
                                }

                            } else if (VarCodeEnum.CFALL.getName().equals(tplName)) {
                                //儿童跌倒/坠床评分
                                if(score>=12){
                                    map.put("colorFlag","1");
                                }

                            } else if (VarCodeEnum.BRADENQ.getName().equals(tplName)) {
                                //Braden-Q评分
                                if(score<=10 || (score>=11 && score<=21)){
                                    map.put("colorFlag","4");
                                }
                            } else if (VarCodeEnum.NUTRITIONAL_RISK.getName().equals(tplName)) {
                                //营养风险筛查NRS2002评分
                            } else if (VarCodeEnum.CATHETER_SLIPPAGE.getName().equals(tplName)) {
                                //导管滑脱危险因素评分
                                if(score>12){
                                    map.put("colorFlag","5");
                                }
                            } else if (VarCodeEnum.BARTHEL.getName().equals(tplName)) {
                                //Barthel评分
                                if(score<=40){
                                    map.put("colorFlag","6");
                                }
                            }else if(VarCodeEnum.BRADEN.getName().equals(tplName)){
                                //Braden评分
                                if(score<9 || (score>=10 && score<=14)){
                                    map.put("colorFlag","4");
                                }
                            }
                        }
                    }else if(org.apache.commons.lang3.StringUtils.isNotBlank(detailValue.get("varCode")) && ( VarCodeEnum.PGSJ.getVarCode().equals(detailValue.get("varCode"))
                            || VarCodeEnum.NUTRITIONAL_RISK_PGSJ.getVarCode().equals(detailValue.get("varCode")))){
                        map.put("emrTime", (detailValue.get("DATA_VALUE")==null ? "" : detailValue.get("DATA_VALUE"))+(detailValue.get("UNIT")==null ? "" : detailValue.get("UNIT")));
                        map.put(detailValue.get("ELEMENT_ID"), (detailValue.get("DATA_VALUE")==null ? "" : detailValue.get("DATA_VALUE"))+(detailValue.get("UNIT")==null ? "" : detailValue.get("UNIT")));
                    }
                }
            });
            list.add(map);
        }
        tableDTO.setList(list);
        return tableDTO;
    }

    private static String comparingByResult(CirculationTemplateDTO circulationTemplateDTO) {
        return circulationTemplateDTO.getResult();
    }

    public Map<String, String> getPatientInfo(String inpatNum) {
        return patientInHospitalMapper.getPatientInfoNurse(inpatNum, null, null);
    }

    /**
     * 修改病人信息
     * @param params
     * @return
     */
    public Result updatePatientInfo(Map<String, String> params){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //入科时间、床位医生、责任护士进行修改
        String doctorPersonId = (String) params.get("doctorPersonId");
        String nurseId = (String) params.get("nurseId");
        String wardDeptId = (String) params.get("wardDeptId");
        String circulationLogId = (String) params.get("circulationLogId");
        String inpatNum = (String) params.get("inpatNum");
        String inDatetime = (String) params.get("inWardDatetime");
        //String bedNo = (String) params.get("bedNo");

        String operationName="";
        String operationId="";


        //根据inpatNum查询病人信息表
        PatientInHospitalEntity patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
        if(patientInHospitalEntity!=null){
            if(StringUtils.isNotBlank(patientInHospitalEntity.getWardDeptId()) && !wardDeptId.equals(patientInHospitalEntity.getWardDeptId())){
                return ResultGenerator.genFailedResult("患者不在此病区不能修改");
            }else{

                Map<String, Object> map1 = new HashMap<>();
                Map<String, Object> requestMap1 = new HashMap<>();
                Map<String, Object> param1 = new HashMap<>();
                param1.put("patient_id", patientInHospitalEntity.getMedicalNum());
                param1.put("visit_id", patientInHospitalEntity.getInpatTimes());
                param1.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
                param1.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));

                requestMap1.put("request", param1);
                map1.put("c_request", requestMap1);
                map1.put("operationID", ConstantEnum.HIS_CIRCULATION_10013.getKey());
                log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map1.toString());
                System.out.println(JSON.toJSONString(map1));
                JSONObject jsonObject1 = HttpClientUtil.sendPost(circulationUrl, map1);
                log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject1));
                if (null != jsonObject1) {
                    Integer resInt = Integer.valueOf((String) jsonObject1.get("Error_Id"));
                    if (resInt < 0) {
                        return ResultGenerator.genFailedResult(jsonObject1.getString("Error_Msg"));
                    } else {
                        if (jsonObject1.getString("c_response") != null) {
                            Map<String, Object> cresponseMap = JSON.parseObject(jsonObject1.getString("c_response"), new TypeReference<Map<String, Object>>() {
                            });
                            Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");
                            if (response != null && response.get("patinfo") != null) {
                                Map<String, Object> patinfo = (Map<String, Object>) response.get("patinfo");
                                //获取手术时间
                                operationName = StringUtils.isNotBlank((String) patinfo.get("operation_name")) ? (String) patinfo.get("operation_name") : "";
                                operationId = StringUtils.isNotBlank((String) patinfo.get("operating_date")) ? (String) patinfo.get("operating_date") : "";
                            }
                        }
                    }
                }

                //his对接
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> requestMap = new HashMap<>();
                Map<String, Object> param = new HashMap<>();
                Map<String, Object> patinfoMap = new HashMap<>();
                param.put("patient_id", patientInHospitalEntity.getMedicalNum());
                param.put("visit_id", patientInHospitalEntity.getInpatTimes());
                param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
                param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
                param.put("computer_name", "");

                patinfoMap.put("adm_ward_date_time", inDatetime);
                patinfoMap.put("cost_emp_no", patientInHospitalMapper.queryUserIdByPersonId(doctorPersonId));
                patinfoMap.put("task_nurse_no", patientInHospitalMapper.queryUserIdByPersonId(nurseId));
                patinfoMap.put("operating_date", operationId);
                patinfoMap.put("operation_name", operationName);
                param.put("patinfo", patinfoMap);

                requestMap.put("request", param);
                map.put("c_request", requestMap);
                map.put("operationID", ConstantEnum.HIS_CIRCULATION_10015.getKey());
                log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
                System.out.println(JSON.toJSONString(map));
                JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
                log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                if (null != jsonObject) {
                    Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                    if (resInt < 0) {
                        return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                    }
                }

                patientInHospitalEntity.setResponsibleDoctorPersonId(doctorPersonId);
                patientInHospitalEntity.setInWardDatetime(DateUtil.dateToTimestamp(DateUtil.stringToDate(inDatetime + ":00", "yyyy-MM-dd HH:mm:ss")));
                patientInHospitalMapper.updateByPrimaryKeySelective(patientInHospitalEntity);
                //设置护士信息
                circulationLogMapper.mergesaveMedicalRecordsOthers(UUIDUtil.randomString(), StateEnum.HOSPITAL_ID.getValue(), inpatNum, nurseId);
                //修改
                //4.增加入院完成日志(待入院信息)
                CirculationLogEntity circulationLogEntity = circulationLogMapper.queryCirculationLogById(circulationLogId);
                if (circulationLogEntity!=null) {
                    //更新入院状态(待入院信息)
                    circulationLogMapper.updateLogById(circulationLogId,userId,nurseId,doctorPersonId);
                }
            }
        }
        return ResultGenerator.genOkResult();
    }

    /**
     * @param wardDeptId
     * @param allFlag 0 不勾选 1勾选
     * @param keyWords
     * @return
     */
    public Result queryWaitNewHospitalList(String wardDeptId,String allFlag,String keyWords,Integer page,Integer pageSize,String operationFlag){
        List<Map<String, String>> list = new CopyOnWriteArrayList<>();
        if(CirculationModelEnum.WAIT_IN_HOSP.getCode().equals(operationFlag)) {
            //入院
            if ("1".equals(allFlag)) {
                wardDeptId = "";
            }
            PageHelper.startPage(page, pageSize);
            list = circulationLogMapper.queryWaitNewHospitalList(wardDeptId, keyWords);
        }else if(CirculationModelEnum.WAIT_OUT_HOSP.getCode().equals(operationFlag)) {
            //出院
            PageHelper.startPage(page, pageSize);
            list = circulationLogMapper.queryWaitOutHospitalList(wardDeptId, keyWords,null,operationFlag,null);

        }else if(CirculationModelEnum.WAIT_IN_DEPT.getCode().equals(operationFlag)) {
            //转入
            PageHelper.startPage(page, pageSize);
            list = circulationLogMapper.queryWaitInDeptList(wardDeptId, keyWords,null,null);
        }else if(CirculationModelEnum.WAIT_OUT_DEPT.getCode().equals(operationFlag)) {
            //转出
            if ("0".equals(allFlag)) {
                //转入
                PageHelper.startPage(page, pageSize);
                list = circulationLogMapper.queryWaitOutHospitalList(wardDeptId, keyWords,null,operationFlag,null);
            }else if ("1".equals(allFlag)) {
                //转科转出
                List<Map<String, String>> list2 = circulationLogMapper.queryWaitOutHospitalList(wardDeptId, keyWords,null,operationFlag,null);
                List<Map<String, String>> resultList = new CopyOnWriteArrayList<>();
                List<Map<String, String>> lastList = new CopyOnWriteArrayList<>();
                List<String> inpatNumList = new CopyOnWriteArrayList<>();
                if(CollectionUtils.isNotEmpty(list2)){
                    list2.stream().forEach(x->{
                        Map<String, String> map = new CopyOnWriteMap<>();
                        inpatNumList.add(x.get("inpatNum"));
                        resultList.add(x);
                    });
                }
                String babyFlag = null;
                List<Map<String, String>> pbstetricWardList = circulationLogMapper.queryObstetricWard(wardDeptId,VarCodeEnum.OBSTETRICS_WARD.getVarCode());
                if(CollectionUtils.isNotEmpty(pbstetricWardList)){
                    babyFlag="1";
                }
                List<Map<String, String>> notCirculationList = circulationLogMapper.queryBedNoByWardDeptId(wardDeptId,null,keyWords,babyFlag,inpatNumList,null);
                if(CollectionUtils.isNotEmpty(notCirculationList)){
                    notCirculationList.stream().forEach(x->{
                        x.put("circulationLogId","");
                        x.put("circulationModelType",operationFlag);
                        resultList.add(x);
                    });
                }
                int totalLength = 0;
                //排序
                if (CollectionUtils.isNotEmpty(resultList)) {
                    lastList = resultList.stream().sorted(Comparator.comparingInt(PatientCirculationServiceImpl::comparingByBedNo2))
                                .collect(Collectors.toList());
                    totalLength = lastList.size();

                    if (page != 0 && pageSize != 0) {
                        lastList = lastList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
                    }
                }
                PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(lastList);
                pageInfo.setTotal(totalLength);
                return ResultGenerator.genOkResult(pageInfo);
            }

        }
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    /**
     * 获取住院登记信息
     * @param inpatNum
     * @return
     */
    public Map<String,Object> getPatinfo(String inpatNum) {
        Map<String, Object> patinfo = new CopyOnWriteMap<>();
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("patient_id", inpatNum.split("-")[0]);
        param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));
        param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
        param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));

        requestMap.put("request", param);
        map.put("c_request", requestMap);
        map.put("operationID", ConstantEnum.HIS_CIRCULATION_10013.getKey());
        log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
        System.out.println(JSON.toJSONString(map));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt > 0) {
                if (jsonObject.getString("c_response") != null) {
                    Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                    });
                    Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");
                    if (response != null && response.get("patinfo") != null) {
                        patinfo = (Map<String, Object>) response.get("patinfo");
                    }
                }
            }
        }
        return patinfo;
    }

    /**
     * 获取费用信息
     * @param inpatNum
     * @return
     */
    public Map<String,String> getCharge(String inpatNum) {
        Map<String, String> chargeMap = new CopyOnWriteMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("operationID","10001");
        param.put("as_patientId",inpatNum.split("-")[0]);
        param.put("al_visitId",Integer.valueOf(inpatNum.split("-")[1]));
        param.put("al_doctor_type","0");
        log.info("10001 --param-- [{}]",JSONObject.toJSONString(param));
        JSONObject jsonObject = HttpClientUtil.sendPost(emrnewUrl, param);
        log.info("10001 --result-- [{}]",jsonObject);
        if (!jsonObject.getJSONArray("data").isEmpty()) {
            JSONObject charge2 = (JSONObject) jsonObject.getJSONArray("data").get(0);
            String yjjAmt = charge2.getString("YJJ_AMT");
            String totalCost = charge2.getString("TOTAL_COST");
            //获取预交金，总费用
            chargeMap.put("yjjAmt",StringUtils.isNotBlank(yjjAmt)?yjjAmt:"0.00");
            chargeMap.put("totalCost",StringUtils.isNotBlank(totalCost)?totalCost:"0.00");
        }
        return chargeMap;
    }

    public Map<String,String> getCurrentDiagName(String inpatNum){
        Map<String,String> diagMap = new CopyOnWriteMap<>();
        String diagName = "";
        String diagId = circulationLogMapper.queryDiagIdByInpatNum(inpatNum);
        if (StringUtils.isNotBlank(diagId)) {
            // 获取护士修改的诊断名称
            diagName = circulationLogMapper.queryDiagByDiagId(diagId);
        } else {
            //取病案首页his出院诊断
            if ("prod".equals(activeType)) {
                String[] inpatNums = inpatNum.split("-");
                String param = "as_patient_id=" + inpatNums[0] + "&al_visit_id=" + inpatNums[1];
                JSONObject jsonObject = HttpConnectUtils.sendGet("http://172.20.91.56:8181/P_VsitInfo_Query_03", param);
                if ("1".equals(jsonObject.get("error_id").toString())) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (Object jsonObject1 : jsonArray) {
                        JSONObject object = JSONObject.parseObject(jsonObject1.toString());
                        if (object.get("DIAGNOSIS_TYPE") != null && "2".equals(object.get("DIAGNOSIS_TYPE").toString())) {
                            diagName = object.get("DIAGNOSIS_DESC").toString();
                            break;
                        }
                    }
                }
            }
            if (StringUtils.isBlank(diagName)) {
                // 获取智慧病历出院诊断/修正诊断/入院诊断
                diagName = circulationLogMapper.queryOutHospitalDiag(inpatNum);
                if (StringUtils.isBlank(diagName)) {
                    //获取his门诊诊断
                    diagName = circulationLogMapper.queryOutpatientDiag(inpatNum);
                }
            }
        }
        if(StringUtils.isNotBlank(diagName)){
            diagMap.put("diagName",diagName);
            diagMap.put("diagId",circulationLogMapper.queryDiagByDiagName(diagName));
        }else{
            diagMap.put("diagName","");
            diagMap.put("diagId","");
        }
        return diagMap;
    }

    /**
     * 查询病人信息
     * @param circulationLogId
     * @param inpatNum
     * @return
     */
    public Result queryPatientInfo(String circulationLogId,String inpatNum,String operationFlag){
        PatientInHospitalDTO patientInHospitalEntity = null;
        //根据住院号查询
        if(CirculationModelEnum.WAIT_OUT_HOSP.getCode().equals(operationFlag)){
            patientInHospitalEntity = patientInHospitalMapper.selectPatientOutHospByInpatNum(inpatNum, circulationLogId,operationFlag);
            getPatientAge(patientInHospitalEntity);
            //出院信息
            Map<String, String> chargeMap = this.getCharge(inpatNum);
            Map<String, Object> patinfoMap = this.getPatinfo(inpatNum);
            Map<String, String> diagMap = circulationLogMapper.queryOutpatientDiag3(inpatNum, "4");
            if (diagMap != null) {
                patientInHospitalEntity.setDiagId(diagMap.get("diagId"));
                patientInHospitalEntity.setDiagName(diagMap.get("diagName"));
            }
            if (chargeMap != null) {
                patientInHospitalEntity.setYjjAmt(chargeMap.get("yjjAmt"));
                patientInHospitalEntity.setTotalCost(chargeMap.get("totalCost"));
            }
            if (patinfoMap != null) {
                patientInHospitalEntity.setMedicalType(getYllbName((String)patinfoMap.get("yllb")));
                patientInHospitalEntity.setMedicalTypeId((String)patinfoMap.get("yllb"));
                patientInHospitalEntity.setPaymentMethod((String) patinfoMap.get("charge_type"));
            }
            patientInHospitalEntity.setOperationFlag(operationFlag);
        }else if(CirculationModelEnum.WAIT_IN_DEPT.getCode().equals(operationFlag)) {
            //转入
            patientInHospitalEntity = patientInHospitalMapper.selectPatientOutHospByInpatNum(inpatNum, circulationLogId,operationFlag);
            getPatientAge(patientInHospitalEntity);
            //出院信息
            Map<String, Object> patinfoMap = this.getPatinfo(inpatNum);
            Map<String, String> diagMap = this.getCurrentDiagName(inpatNum);
            //获取实时的诊断
            if (patinfoMap != null) {
                patientInHospitalEntity.setPaymentMethod((String) patinfoMap.get("charge_type"));
                patientInHospitalEntity.setMedicaCardNum((String) patinfoMap.get("insurance_no"));
                //获取手术时间
                String operationName = "";
                if (StringUtils.isNotBlank((String) patinfoMap.get("operation_name"))) {
                    operationName = (String) patinfoMap.get("operation_name");
                }
                patientInHospitalEntity.setOperationTime(StringUtils.isNotBlank((String) patinfoMap.get("operating_date")) ? (String) patinfoMap.get("operating_date") : "");
                patientInHospitalEntity.setOperationName(operationName);
            }
            if (diagMap != null) {
                patientInHospitalEntity.setDiagId(diagMap.get("diagId"));
                patientInHospitalEntity.setDiagName(diagMap.get("diagName"));
            }
            patientInHospitalEntity.setOperationFlag(operationFlag);
        }else if(CirculationModelEnum.WAIT_OUT_DEPT.getCode().equals(operationFlag)) {
            //转出
            patientInHospitalEntity = patientInHospitalMapper.selectPatientOutHospByInpatNum(inpatNum, circulationLogId,operationFlag);
            getPatientAge(patientInHospitalEntity);
            patientInHospitalEntity.setOperationFlag(operationFlag);
            List<Map<String, String>> wardDeptList = circulationLogMapper.queryWardDeptByDeptId(patientInHospitalEntity.getTransferInDeptId(), null, null);
            if(CollectionUtils.isNotEmpty(wardDeptList)){
                patientInHospitalEntity.setTransferInWardDeptId(wardDeptList.get(0).get("id"));
                patientInHospitalEntity.setTransferInWardDeptName(wardDeptList.get(0).get("name"));
            }
            if(StringUtils.isBlank(circulationLogId)){
                patientInHospitalEntity.setCirculationLogId("");
            }
        }else {
            patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum2(inpatNum);
            getPatientAge(patientInHospitalEntity);
            patientInHospitalEntity.setCirculationLogId(circulationLogId);
            patientInHospitalEntity.setOperationFlag(operationFlag);
            //入院信息
            Map<String, String> diagMap = circulationLogMapper.queryOutpatientDiag3(inpatNum, "0");
            if (diagMap != null) {
                patientInHospitalEntity.setDiagId(diagMap.get("diagId"));
                patientInHospitalEntity.setDiagName(diagMap.get("diagName"));
            }
            patientInHospitalEntity.setInDeptId(patientInHospitalEntity.getDeptId());
            patientInHospitalEntity.setInDeptName(patientInHospitalEntity.getDeptName());
            if (StringUtils.isNotBlank(patientInHospitalEntity.getWardDeptId())) {
                patientInHospitalEntity.setInWardDeptId(patientInHospitalEntity.getWardDeptId());
            }
            if (StringUtils.isNotBlank(patientInHospitalEntity.getWardDeptName())) {
                patientInHospitalEntity.setInWardDeptName(patientInHospitalEntity.getWardDeptName());
            }

            //1.调用HIS接口
            Map<String, Object> patinfo = this.getPatinfo(inpatNum);
            if (patinfo!=null) {
                patientInHospitalEntity.setOutpatNum((String) patinfo.get("inp_no"));
                patientInHospitalEntity.setMedicaCardNum((String) patinfo.get("insurance_no"));
                patientInHospitalEntity.setMedicalType(getYllbName((String) patinfo.get("yllb")));
                patientInHospitalEntity.setPaymentMethod((String) patinfo.get("charge_type"));
                patientInHospitalEntity.setMedicalStaffType((String) patinfo.get("yb_name"));
                patientInHospitalEntity.setOutpatientDoctorPersonName((String) patinfo.get("consulting_doctor"));
                patientInHospitalEntity.setOutpatientDoctorPersonId((String) patinfo.get("consulting_doctor"));
                patientInHospitalEntity.setObjectiveName((String) patinfo.get("admission_cause"));
                patientInHospitalEntity.setObjectiveId((String) patinfo.get("admission_cause"));
                patientInHospitalEntity.setAgent((String) patinfo.get("admitted_by"));
                patientInHospitalEntity.setPersonTypeName((String) patinfo.get("identity"));
                patientInHospitalEntity.setPersonTypeId((String) patinfo.get("identity"));
                patientInHospitalEntity.setDayWardFlag("1".equals((String) patinfo.get("day_ward_flag")) ? "1" : "0");
                String receiveTime = (String) patinfo.get("consulting_date");
                patientInHospitalEntity.setReceiveTime(receiveTime == null ? null : new Timestamp(DateUtil.stringToDate(receiveTime, "yyyy-MM-dd HH:mm:ss").getTime()));
                //获取手术时间
                String operationName = "";
                if (StringUtils.isNotBlank((String) patinfo.get("operation_name"))) {
                    operationName = (String) patinfo.get("operation_name");
                }
                patientInHospitalEntity.setOperationTime(StringUtils.isNotBlank((String) patinfo.get("operating_date")) ? (String) patinfo.get("operating_date") : "");
                patientInHospitalEntity.setOperationName(operationName);
                patientInHospitalEntity.setPatinfo(patinfo);
            }
        }
        //调用his接口
        return ResultGenerator.genOkResult(patientInHospitalEntity);
    }

    private void getPatientAge(PatientInHospitalDTO patientInHospitalEntity) {
        Integer ageYear = patientInHospitalEntity.getAgeYear() == null ? 0 : patientInHospitalEntity.getAgeYear();
        Integer ageMonth = patientInHospitalEntity.getAgeMonth() == null ? 0 : patientInHospitalEntity.getAgeMonth();
        Integer ageDay = patientInHospitalEntity.getAgeYear() == null ? 0 : patientInHospitalEntity.getAgeYear();
        Integer ageHour = patientInHospitalEntity.getAgeHour() == null ? 0 : patientInHospitalEntity.getAgeHour();
        Integer ageMinute = patientInHospitalEntity.getAgeMinute() == null ? 0 : patientInHospitalEntity.getAgeMinute();
        StringBuffer ageStr = new StringBuffer();
        if (ageYear != 0) {
            ageStr.append(ageYear + "岁");
            patientInHospitalEntity.setAge(ageStr.toString());
            return;
        }
        if (ageMonth != 0) {
            ageStr.append(ageMonth + "月");
        }
        if (ageDay != 0) {
            ageStr.append(ageDay + "天");
        }
        if (ageHour != 0) {
            if (ageDay < 29) {              //28天以上不需要小时
                ageStr.append(ageHour + "小时");
            }
        }
        if (ageMinute != 0) {
            ageStr.append(ageMinute + "分钟");
        }
        if (ageStr.length() == 0) {
            ageStr.append(ageHour + "小时");
            ageStr.append(ageMinute + "分钟");
        }
        patientInHospitalEntity.setAge(ageStr.toString());
    }

    public Result queryDropDown(String dataVersionId,String serialNumber,String dataValueId,String keyWords,Integer page,Integer pageSize){
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = patientInHospitalMapper.queryDropDown(dataVersionId, serialNumber, dataValueId,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryReligionList(String basicdatavalueId,String keyWords,Integer page,Integer pageSize){
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = patientInHospitalMapper.queryReligionList(basicdatavalueId,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryDiagnosisList(String diagId,String keyWords,Integer page,Integer pageSize){
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = patientInHospitalMapper.queryDiagnosisList(diagId,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryOperationList(String id,String keyWords,Integer page,Integer pageSize){
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = patientInHospitalMapper.queryOperationList(id,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result saveNewHospitalList(PatientInHospitalDTO patientInHospitalDTO){
        //
        String inpatNum = patientInHospitalDTO.getInpatNum();
        String bedNo = patientInHospitalDTO.getBedNo();
        String deptId = patientInHospitalDTO.getInDeptId();
        String doctorPersonId = patientInHospitalDTO.getResponsibleDoctorPersonId();
        String inDatetime = DateUtil.dateToString(patientInHospitalDTO.getInDatetime(),"yyyy-MM-dd HH:mm");
        String inWardDatetime = DateUtil.dateToString(patientInHospitalDTO.getInWardDatetime(),"yyyy-MM-dd HH:mm");
        String nurseId = patientInHospitalDTO.getResponsibleNursePersonId();
        String wardDeptId = patientInHospitalDTO.getInWardDeptId();
        String circulationLogId = patientInHospitalDTO.getCirculationLogId();
        String diagId =  patientInHospitalDTO.getDiagId();
        //String diagIcd = patientInHospitalDTO.getDiagIcd();
        //String diagName = patientInHospitalDTO.getDiagName();
        String diagIcd = "";
        String diagName = "";

        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        UserEntity currentUser = userMapper.selectByPrimaryKey(userId);
        PatientInHospitalEntity patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum(inpatNum);
        Map<String, String> oldRes = patientInHospitalMapper.queryPatientOtherInfo(inpatNum);
        //查询医生对应的emp_no,dept_code,诊断名称，诊断ICD，责任护士工号
        Map<String, String> res = new CopyOnWriteMap<>();
        if(StringUtils.isNotBlank(diagId)){
            res = patientInHospitalMapper.queryDiagById(diagId);
            if(res!=null){
                diagIcd=res.get("diagIcd");
                diagName=res.get("diagName");
            }
        }

        if("insert".equals(patientInHospitalDTO.getFlag())) {
            //根据用户id获取工号
            //1.调用HIS接口
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> requestMap = new HashMap<>();
            Map<String, Object> param = new HashMap<>();
            param.put("patient_id", patientInHospitalEntity.getMedicalNum());
            param.put("visit_id", patientInHospitalEntity.getInpatTimes());
            param.put("operator", currentUser.getUserName());
            param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
            param.put("dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(deptId));
            param.put("bed_no", Integer.valueOf(bedNo));
            param.put("admission_date_time", inDatetime + ":00");
            param.put("adm_ward_date_time", inWardDatetime + ":00");
            param.put("cost_emp_no", patientInHospitalMapper.queryUserIdByPersonId(doctorPersonId));
            param.put("diagnosis", diagName != null ? diagName : "");
            param.put("diagnosis_icd", diagIcd != null ? diagIcd : "");
            param.put("task_nurse_no", patientInHospitalMapper.queryUserIdByPersonId(nurseId));
            param.put("operationID", ConstantEnum.HIS_CIRCULATION_10041.getKey());
            param.put("operating_date", "");
            param.put("operation_name", "");
            param.put("patient_condition", "");
            param.put("cell", "");
            param.put("operation_code", "");
            requestMap.put("request", param);
            map.put("c_request", requestMap);
            map.put("operationID", ConstantEnum.HIS_CIRCULATION_10041.getKey());
            log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
            System.out.println(JSON.toJSONString(map));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, map);
            if (jsonObject.isEmpty()) {
                return ResultGenerator.genFailedResult("患者入院失败");
            }
            log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
        }

        //修改门诊诊断  判断门诊诊断是否修改
        boolean diagUpdateFlag = true;
        if(oldRes!=null){
            if(StringUtils.isNotBlank(oldRes.get("DIAG_ID")) && oldRes.get("DIAG_ID").equals(diagId)){
                diagUpdateFlag=false;
            }else if(oldRes.get("DIAG_ID")==null && !StringUtils.isNotBlank(diagId)){
                diagUpdateFlag=false;
            }
        }
        if(diagUpdateFlag){
            circulationLogMapper.updateDiagByInpatNum(inpatNum,diagId);
        }

        //更新病人信息
        //添加流转信息
        //2.保存病人信息
        updatePatientInfo(patientInHospitalEntity,patientInHospitalDTO,inDatetime,inWardDatetime);
        patientInHospitalMapper.updateByPrimaryKeySelective(patientInHospitalEntity);

        //设置护士信息
        circulationLogMapper.mergesaveMedicalRecordsOthers(UUIDUtil.randomString(), StateEnum.HOSPITAL_ID.getValue(), inpatNum, nurseId);

        //取床号别名
        String bedLabel = circulationLogMapper.queryBedLabel(wardDeptId, inpatNum);

        if("insert".equals(patientInHospitalDTO.getFlag())) {
            //4.增加入院完成日志(待入院信息)
            CirculationLogEntity circulationLogEntity = circulationLogMapper.queryCirculationLogById(circulationLogId);
            if (null == circulationLogEntity) {
                return ResultGenerator.genOkResult();
            }
            circulationLogEntity.setInNurseId(nurseId);
            circulationLogEntity.setInWardDeptId(wardDeptId);
            circulationLogEntity.setInDoctorPersonId(doctorPersonId);
            circulationLogEntity.setInBedNo(bedNo);
            circulationLogEntity.setInBedLabel(bedLabel);
            circulationLogEntity.setInDeptId(deptId);
            circulationLogEntity.setStatus(1);
            circulationLogEntity.setOperator(userId);
            //更新入院状态(待入院信息)
            circulationLogMapper.updateByPrimaryKeySelective(circulationLogEntity);

            //增加入院完成日志
            CirculationLogEntity inHosEntity = new CirculationLogEntity();
            inHosEntity.initAdd();
            inHosEntity.setStatus(1);
            inHosEntity.setCirculationLogId(UUIDUtil.randomString());
            inHosEntity.setCirculationModelType(CirculationModelEnum.FINISH_IN_HOSP.getCode());
            inHosEntity.setCirculationOperateType(CirculationTypeEnum.IN_HOSP.getCode());
            inHosEntity.setHealthNum(patientInHospitalEntity.getHealthNum());
            inHosEntity.setInBedNo(bedNo);
            inHosEntity.setInBedLabel(bedLabel);
            inHosEntity.setInDatetime(DateUtil.stringToDate(inDatetime + ":00", "yyyy-MM-dd HH:mm:ss"));
            inHosEntity.setInDeptId(deptId);
            inHosEntity.setInDoctorPersonId(doctorPersonId);
            inHosEntity.setInNurseId(nurseId);
            inHosEntity.setInpatNum(inpatNum);
            inHosEntity.setInWardDeptId(wardDeptId);
            inHosEntity.setPatTypeId(patientInHospitalEntity.getPatTypeId());
            inHosEntity.setSerialNo(null == circulationLogEntity.getSerialNo() ? 1 : circulationLogEntity.getSerialNo() + 1);
            inHosEntity.setSourceType(Constant.SELF);
            inHosEntity.setBatchNo(circulationLogEntity.getBatchNo());
            inHosEntity.setOperator(userId);
            circulationLogMapper.insert(inHosEntity);

            //更新床号
            circulationLogMapper.updateBedNoStatus(bedNo, wardDeptId, "1");
        }

        //获取patinfo的信息
        Map<String, Object> patinfo = patientInHospitalDTO.getPatinfo();
        if(patinfo!=null) {
            //更新住院登记信息
            //根据用户id获取工号
            //1.调用HIS接口
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> requestMap = new HashMap<>();
            Map<String, Object> param = new HashMap<>();
            Map<String, Object> patinfoMap = new HashMap<>();
            param.put("patient_id", patientInHospitalEntity.getMedicalNum());
            param.put("visit_id", patientInHospitalEntity.getInpatTimes());
            param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
            param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            patinfoMap.put("sex", patinfo.get("sex"));
            patinfoMap.put("date_of_birth", patinfo.get("date_of_birth"));
            patinfoMap.put("age", patinfo.get("age"));
            patinfoMap.put("unit", patinfo.get("unit"));
            patinfoMap.put("identity", patinfo.get("identity"));
            patinfoMap.put("marital_status", patientInHospitalDTO.getMarriageName());//婚姻
            patinfoMap.put("birth_place_code", getPlaceCode(patientInHospitalDTO.getBirthProvinceId(),patientInHospitalDTO.getBirthCityId(),patientInHospitalDTO.getBirthCountyId()));//出生地
            patinfoMap.put("birth_place_street", patientInHospitalDTO.getBirthTownship());//街村
            patinfoMap.put("place_of_origin", getPlaceCode(patientInHospitalDTO.getOriginProvinceId(),patientInHospitalDTO.getOriginCityId(),patientInHospitalDTO.getOriginCountyId()));//籍贯
            Map<String, String> queryMap = circulationLogMapper.querySysPrimaryDataValueById(patientInHospitalDTO.getOccupationTypeId());
            if(StringUtils.isNotBlank(patientInHospitalDTO.getOccupationTypeId())){
                queryMap = circulationLogMapper.querySysPrimaryDataValueById(patientInHospitalDTO.getOccupationTypeId());
                patinfoMap.put("occupation", queryMap==null?"":queryMap.get("dataValue")!=null?queryMap.get("dataValue"):"");//职业-编码
            }else{
                patinfoMap.put("occupation", "");//联系人-关系
            }

            if(StringUtils.isNotBlank(patientInHospitalDTO.getCountryId())){
                queryMap = circulationLogMapper.queryHisDictCodeById(patientInHospitalDTO.getCountryId());
                patinfoMap.put("citizenship", queryMap==null?"":queryMap.get("hisDictCode")!=null?queryMap.get("hisDictCode"):"");//职业-编码
            }else{
                patinfoMap.put("citizenship", "");//联系人-关系
            }

            patinfoMap.put("nation", patientInHospitalDTO.getNationName());//民族-名称

            if(StringUtils.isNotBlank(patientInHospitalDTO.getIdTypeId())){
                queryMap = circulationLogMapper.queryHisDictCodeById(patientInHospitalDTO.getIdTypeId());
                patinfoMap.put("id_no_type", queryMap==null?"":queryMap.get("hisDictCode")!=null?queryMap.get("hisDictCode"):"");//职业-编码
            }else{
                patinfoMap.put("id_no_type", "");//联系人-关系
            }

            patinfoMap.put("id_no", patientInHospitalDTO.getIdNum()); //身份证号
            patinfoMap.put("curr_place", getPlaceCode(patientInHospitalDTO.getAddressProvinceId(),patientInHospitalDTO.getAddressCityId(),patientInHospitalDTO.getAddressCountyId()));//现住址
            patinfoMap.put("curr_addr", patientInHospitalDTO.getAddressTownship());//现住址-街村
            patinfoMap.put("phone_number_home", patientInHospitalDTO.getPhoneNum());//现住址-电话
            patinfoMap.put("curr_zip_code", patientInHospitalDTO.getAddressZipCode());//现住址邮编
            patinfoMap.put("stay_place", getPlaceCode(patientInHospitalDTO.getRegistProvinceId(),patientInHospitalDTO.getRegistCityId(),patientInHospitalDTO.getRegistCountyId()));//户口地址
            patinfoMap.put("mailing_address", patientInHospitalDTO.getRegistTownship());//户口地址-街村
            patinfoMap.put("next_of_kin_zipcode", patientInHospitalDTO.getRegistZipCode());//户口地址邮编
            patinfoMap.put("service_agency", patientInHospitalDTO.getWorkUnit());//单位地址
            patinfoMap.put("phone_number_business", patientInHospitalDTO.getWorkPhoneNum());//单位地址-电话
            patinfoMap.put("zip_code", patientInHospitalDTO.getWorkZipCode());//单位地址-邮编
            patinfoMap.put("next_of_kin", patientInHospitalDTO.getContactsName());//联系人
            if(StringUtils.isNotBlank(patientInHospitalDTO.getRelationshipId())){
                queryMap = circulationLogMapper.querySysPrimaryDataValueById(patientInHospitalDTO.getRelationshipId());
                patinfoMap.put("relationship", queryMap==null?"":queryMap.get("dataValue")!=null?queryMap.get("dataValue"):"");//联系人-关系
            }else{
                patinfoMap.put("relationship", "");//联系人-关系
            }
            patinfoMap.put("pos_place", getPlaceCode(patientInHospitalDTO.getContactsProvinceId(),patientInHospitalDTO.getContactsCityId(),patientInHospitalDTO.getContactsCountyId()));//联系人-地址
            patinfoMap.put("next_of_kin_addr",patientInHospitalDTO.getContactsTownship());//联系人-街村
            patinfoMap.put("next_of_kin_phone", patientInHospitalDTO.getContactsPhoneNum());//联系人-电话
            param.put("patinfo", patinfoMap);
            requestMap.put("request", param);
            map.put("c_request", requestMap);
            map.put("operationID", ConstantEnum.HIS_CIRCULATION_10014.getKey());
            log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
            System.out.println(JSON.toJSONString(map));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
            log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
        }

        //更新手术名称和时间
        Map<String, String> operationMap = this.updateOperation(inpatNum, userId, inWardDatetime, doctorPersonId, nurseId, patientInHospitalDTO.getOperationTime(), patientInHospitalDTO.getOperationName());
        if(operationMap!=null && !operationMap.isEmpty()){
            Integer resInt = Integer.valueOf(operationMap.get("Error_Id"));
            if (resInt < 0) {
                return ResultGenerator.genFailedResult(operationMap.get("Error_Msg"));
            }
        }
        return ResultGenerator.genOkResult();
    }

    public Map<String,String> updateOperation(String inpatNum,String userId,String inWardDatetime,String doctorPersonId,String nurseId,
                                  String operationTime,String operationName){
        Map<String,String> result = new CopyOnWriteMap<>();
        //his对接
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> patinfoMap = new HashMap<>();
        param.put("patient_id", inpatNum.split("-")[0]);
        param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));
        param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
        param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        param.put("computer_name", "");

        patinfoMap.put("adm_ward_date_time", inWardDatetime);
        patinfoMap.put("cost_emp_no", patientInHospitalMapper.queryUserIdByPersonId(doctorPersonId));
        patinfoMap.put("task_nurse_no", patientInHospitalMapper.queryUserIdByPersonId(nurseId));
        patinfoMap.put("operating_date",operationTime);
        patinfoMap.put("operation_name", operationName);
        param.put("patinfo", patinfoMap);

        requestMap.put("request", param);
        map.put("c_request", requestMap);
        map.put("operationID", ConstantEnum.HIS_CIRCULATION_10015.getKey());
        log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
        System.out.println(JSON.toJSONString(map));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            result.put("Error_Id",(String) jsonObject.get("Error_Id"));
            result.put("Error_Msg",(String) jsonObject.get("Error_Msg"));
        }
        return result;
    }

    /**
     * 转科转入保存
     * @param patientInHospitalDTO
     * @return
     */
    @Transactional
    public Result saveTranferInDept(PatientInHospitalDTO patientInHospitalDTO){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String inpatNum = patientInHospitalDTO.getInpatNum();
        String bedNo = patientInHospitalDTO.getBedNo();
        String doctorPersonId = patientInHospitalDTO.getResponsibleDoctorPersonId();
        String nurseId = patientInHospitalDTO.getResponsibleNursePersonId();
        //转入科室
        //String transferInDeptId = patientInHospitalDTO.getTransferInDeptId();
        //转入病区
        //String transferInWardDeptId = patientInHospitalDTO.getTransferInWardDeptId();
        String circulationLogId = patientInHospitalDTO.getCirculationLogId();
        String transferInDateTime = DateUtil.dateToString(patientInHospitalDTO.getInWardDatetime(),"yyyy-MM-dd HH:mm");

        CirculationLogEntity circulationLogEntity = circulationLogMapper.queryCirculationLogById(circulationLogId);
        if (circulationLogEntity == null) {
            return ResultGenerator.genFailedResult("此病人无待转入记录");
        } else {
            String deptId = circulationLogEntity.getInDeptId();
            if (StringUtils.isBlank(deptId)) {
                return ResultGenerator.genFailedResult("数据异常,日志中无转入科室");
            }
            Map<String, String> patient = patientService.getPatientInfoNurse(inpatNum, null, null, null, circulationLogId);
            //his接口
            //调用转科his接口
            Map<String, Object> param = new HashMap<>();
            //病人编码 住院号
            param.put("p_patient_id", patient.get("medicalNum"));
            //就诊次数 住院号-后的值
            param.put("p_visit_id", patient.get("inpatTimes"));
            //床号
            param.put("p_bed_no", bedNo);
            //科室代码
            param.put("p_dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(circulationLogEntity.getInDeptId()));
            //病区代码
            param.put("p_ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(circulationLogEntity.getInWardDeptId()));
            //入院时间
            param.put("p_in_date", patient.get("inTime"));
            //转入时间
            param.put("p_in_dept_date", transferInDateTime+":00");
            //责任医生
            param.put("p_doctor", patientInHospitalMapper.queryUserIdByPersonId(doctorPersonId));
            //责任护士
            param.put("p_nurse", patientInHospitalMapper.queryUserIdByPersonId(nurseId));
            //入科操作码
            param.put("operationID", ConstantEnum.HIS_CIRCULATION_10032.getKey());

            System.out.println(JSON.toJSONString(param));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, param);
            if (jsonObject.isEmpty()) {
                return ResultGenerator.genFailedResult("患者转科转入失败");
            }
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            }

            circulationLogEntity.setInNurseId(nurseId);
            circulationLogEntity.setInDoctorPersonId(doctorPersonId);
            circulationLogEntity.setInBedNo(bedNo);
            circulationLogEntity.setInDatetime(DateUtil.stringToDate(transferInDateTime+":00","yyyy-MM-dd HH:mm:ss"));
            circulationLogEntity.setOperator(userId);
            circulationLogEntity.setStatus(1);
            //更新入院状态
            circulationLogMapper.updateByPrimaryKeySelective(circulationLogEntity);

            circulationLogMapper.updatePatient(inpatNum, bedNo, deptId, circulationLogEntity.getInWardDeptId(), doctorPersonId, nurseId);
            //设置护士信息
            circulationLogMapper.mergesaveMedicalRecordsOthers(UUIDUtil.randomString(), StateEnum.HOSPITAL_ID.getValue(), inpatNum, nurseId);
            //更新床号
            circulationLogMapper.updateBedNoStatus(bedNo, circulationLogEntity.getInWardDeptId(), "1");

            CirculationLogEntity entity2 = new CirculationLogEntity();//已转入日志
            entity2.initAdd();
            entity2.setStatus(Integer.parseInt(StateEnum.COMPLETED.getValue()));//已完成
            entity2.setCirculationLogId(UUIDUtil.randomString());
            entity2.setCirculationModelType(CirculationModelEnum.FINISH_IN_DEPT.getCode());
            entity2.setCirculationOperateType(CirculationTypeEnum.TRANSFERRED_DEPT.getCode());
            entity2.setInpatNum(inpatNum);
            entity2.setOutDatetime(circulationLogEntity.getOutDatetime());
            entity2.setInDatetime(DateUtil.stringToDate(transferInDateTime+":00","yyyy-MM-dd HH:mm:ss"));
            entity2.setInpatorderdataId(circulationLogEntity.getInpatorderdataId());

            entity2.setInDeptId(circulationLogEntity.getInDeptId());
            entity2.setOutDeptId(circulationLogEntity.getOutDeptId());

            entity2.setSourceType("SELF");
            entity2.setSerialNo(circulationLogEntity.getSerialNo() == null ? 1 : circulationLogEntity.getSerialNo() + 1);
            entity2.setCancelFlag(0);
            entity2.setPatTypeId(circulationLogEntity.getPatTypeId());
            entity2.setHealthNum(circulationLogEntity.getHealthNum());

            entity2.setOutDoctorPersonId(circulationLogEntity.getOutDoctorPersonId());
            entity2.setInDoctorPersonId(doctorPersonId);

            entity2.setInBedNo(bedNo);
            entity2.setInBedLabel(circulationLogMapper.queryBedLabel(circulationLogEntity.getInWardDeptId(),bedNo));
            entity2.setOutBedNo(circulationLogEntity.getOutBedNo());
            String outBedLabel = circulationLogMapper.queryBedLabel(circulationLogEntity.getOutWardDeptId(),circulationLogEntity.getOutBedNo());
            entity2.setOutBedLabel(StringUtils.isNotBlank(outBedLabel)?outBedLabel:circulationLogEntity.getOutBedLabel());

            entity2.setInWardDeptId(circulationLogEntity.getInWardDeptId());
            entity2.setOutWardDeptId(circulationLogEntity.getOutWardDeptId());

            entity2.setInNurseId(nurseId);
            entity2.setOutNurseId(circulationLogEntity.getOutNurseId());

            entity2.setOperator(userId);
            circulationLogMapper.insert(entity2);

            //根据CIRCULATION_LOG_ID查询COMMON_TASK_CIRCULATION表信息
            List<String> commonTaskCirculationIds = commonTaskCirculationMapper.selectByCirculationLogId(circulationLogId);
            //更新COMMON_TASK_CIRCULATION表中的CIRCULATION_LOG_ID字段值
            if (CollectionUtils.isNotEmpty(commonTaskCirculationIds)) {
                commonTaskCirculationMapper.updateByCirculationLogId(commonTaskCirculationIds, entity2.getCirculationLogId());
            }

            //更新手术名称和时间
            Map<String, String> operationMap = this.updateOperation(inpatNum, userId, transferInDateTime, doctorPersonId, nurseId, patientInHospitalDTO.getOperationTime(), patientInHospitalDTO.getOperationName());
            if(operationMap!=null && !operationMap.isEmpty()){
                Integer resInt2 = Integer.valueOf(operationMap.get("Error_Id"));
                if (resInt2 < 0) {
                    return ResultGenerator.genFailedResult(operationMap.get("Error_Msg"));
                }
            }
        }
        return ResultGenerator.genOkResult();
    }

    public String getPlaceCode(String provinceId,String cityId,String countryId){
        String value = null;
        String dataValue = "";
        if(StringUtils.isNotBlank(provinceId)){
            value = provinceId;
        }
        if(StringUtils.isNotBlank(cityId)){
            value = cityId;
        }
        if(StringUtils.isNotBlank(countryId)){
            value = countryId;
        }
        if(StringUtils.isNotBlank(value)){
            Map<String, String> map = circulationLogMapper.querySysPrimaryDataValueById(value);
            if(map!=null) {
                dataValue = map.get("dataValue");
            }
        }
        return dataValue;
    }

    public void updatePatientInfo(PatientInHospitalEntity patientInHospitalEntity,PatientInHospitalDTO oldPatientInfo,String inDatetime,String inWardDatetime){
        patientInHospitalEntity.setBedNo(oldPatientInfo.getBedNo());
        patientInHospitalEntity.setDeptId(StringUtils.isNotBlank(oldPatientInfo.getInDeptId())?oldPatientInfo.getInDeptId():oldPatientInfo.getDeptId());
        if(!"update".equals(oldPatientInfo.getFlag())) {
            patientInHospitalEntity.setInDeptId(StringUtils.isNotBlank(oldPatientInfo.getInDeptId()) ? oldPatientInfo.getInDeptId() : oldPatientInfo.getDeptId());
            patientInHospitalEntity.setInWardDeptId(oldPatientInfo.getInWardDeptId());
        }
        patientInHospitalEntity.setWardDeptId(oldPatientInfo.getInWardDeptId());
        patientInHospitalEntity.setInWayId(oldPatientInfo.getInWayId());
        patientInHospitalEntity.setInDatetime(DateUtil.dateToTimestamp(DateUtil.stringToDate(inDatetime + ":00", "yyyy-MM-dd HH:mm:ss")));
        patientInHospitalEntity.setInWardDatetime(DateUtil.dateToTimestamp(DateUtil.stringToDate(inWardDatetime + ":00", "yyyy-MM-dd HH:mm:ss")));
        patientInHospitalEntity.setResponsibleDoctorPersonId(oldPatientInfo.getResponsibleDoctorPersonId());
        //patientInHospitalEntity.setResponsibleNursePersonId(oldPatientInfo.getResponsibleNursePersonId());
        //patientInHospitalEntity.setOperationTime(oldPatientInfo.getOperationTime());
        //patientInHospitalEntity.setOperationName(oldPatientInfo.getOperationName());
        patientInHospitalEntity.setDayWardFlag(oldPatientInfo.getDayWardFlag());
        patientInHospitalEntity.setCountryId(oldPatientInfo.getCountryId());
        patientInHospitalEntity.setIdTypeId(oldPatientInfo.getIdTypeId());
        patientInHospitalEntity.setIdNum(oldPatientInfo.getIdNum());
        patientInHospitalEntity.setNationId(oldPatientInfo.getNationId());
        patientInHospitalEntity.setOccupationTypeId(oldPatientInfo.getOccupationTypeId());
        patientInHospitalEntity.setMarriageId(oldPatientInfo.getMarriageId());
        patientInHospitalEntity.setReligion(oldPatientInfo.getReligion());
        patientInHospitalEntity.setAddressProvinceId(oldPatientInfo.getAddressProvinceId());
        patientInHospitalEntity.setAddressCityId(oldPatientInfo.getAddressCityId());
        patientInHospitalEntity.setAddressCountyId(oldPatientInfo.getAddressCountyId());
        patientInHospitalEntity.setAddressTownship(oldPatientInfo.getAddressTownship());
        patientInHospitalEntity.setPhoneNum(oldPatientInfo.getPhoneNum());
        patientInHospitalEntity.setAddressZipCode(oldPatientInfo.getAddressZipCode());
        patientInHospitalEntity.setContactsName(oldPatientInfo.getContactsName());
        patientInHospitalEntity.setRelationshipId(oldPatientInfo.getRelationshipId());
        patientInHospitalEntity.setContactsProvinceId(oldPatientInfo.getContactsProvinceId());
        patientInHospitalEntity.setContactsCityId(oldPatientInfo.getContactsCityId());
        patientInHospitalEntity.setContactsCountyId(oldPatientInfo.getContactsCountyId());
        patientInHospitalEntity.setContactsTownship(oldPatientInfo.getContactsTownship());
        patientInHospitalEntity.setContactsPhoneNum(oldPatientInfo.getContactsPhoneNum());
        patientInHospitalEntity.setBirthProvinceId(oldPatientInfo.getBirthProvinceId());
        patientInHospitalEntity.setBirthCityId(oldPatientInfo.getBirthCityId());
        patientInHospitalEntity.setBirthCountyId(oldPatientInfo.getBirthCountyId());
        patientInHospitalEntity.setBirthTownship(oldPatientInfo.getBirthTownship());
        patientInHospitalEntity.setOriginProvinceId(oldPatientInfo.getOriginProvinceId());
        patientInHospitalEntity.setOriginCityId(oldPatientInfo.getOriginCityId());
        patientInHospitalEntity.setOriginCountyId(oldPatientInfo.getOriginCountyId());
        patientInHospitalEntity.setRegistProvinceId(oldPatientInfo.getRegistProvinceId());
        patientInHospitalEntity.setRegistCityId(oldPatientInfo.getRegistCityId());
        patientInHospitalEntity.setRegistCountyId(oldPatientInfo.getRegistCountyId());
        patientInHospitalEntity.setRegistTownship(oldPatientInfo.getRegistTownship());
        patientInHospitalEntity.setRegistZipCode(oldPatientInfo.getRegistZipCode());
        patientInHospitalEntity.setWorkUnit(oldPatientInfo.getWorkUnit());
        patientInHospitalEntity.setWorkPhoneNum(oldPatientInfo.getWorkPhoneNum());
        patientInHospitalEntity.setWorkZipCode(oldPatientInfo.getWorkZipCode());
        patientInHospitalEntity.setReligion(oldPatientInfo.getReligion());

    }

    /**
     * 取消入院查询
     * @param wardId
     * @param bedNo
     * @return
     */
    public Result queryFinishNewHospitalList(String wardId, String bedNo,String operationFlag,String inpatNum,String healthNum){
        PatientInHospitalDTO patientInHospitalDTO = new PatientInHospitalDTO();
        if(CirculationModelEnum.CANCLE_IN_HOSP.getCode().equals(operationFlag)) {
            //取消入院
            String babyFlag = null;
            List<Map<String, String>> pbstetricWardList = circulationLogMapper.queryObstetricWard(wardId, VarCodeEnum.OBSTETRICS_WARD.getVarCode());
            if (CollectionUtils.isNotEmpty(pbstetricWardList)) {
                babyFlag = "1";
            }

            patientInHospitalDTO = circulationLogMapper.queryPatientInfoByWardIdAndBedNo(wardId, bedNo, babyFlag);
            if (patientInHospitalDTO != null) {
                getPatientAge(patientInHospitalDTO);
                Map<String, String> diagMap = circulationLogMapper.queryOutpatientDiag3(patientInHospitalDTO.getInpatNum(), "0");
                if (!(diagMap != null && StringUtils.isNotBlank(diagMap.get("diagName")))) {
                    diagMap = circulationLogMapper.queryOutpatientDiag3(patientInHospitalDTO.getInpatNum(), "1");
                    if (diagMap != null && StringUtils.isNotBlank(diagMap.get("diagName"))) {
                        patientInHospitalDTO.setDiagId(diagMap.get("diagId"));
                        patientInHospitalDTO.setDiagName(diagMap.get("diagName"));
                    }
                } else {
                    patientInHospitalDTO.setDiagId(diagMap.get("diagId"));
                    patientInHospitalDTO.setDiagName(diagMap.get("diagName"));
                }
            }
        }else if(CirculationModelEnum.CANCLE_OUT_HOSP.getCode().equals(operationFlag)) {
            if(StringUtils.isBlank(wardId)){
                return ResultGenerator.genFailedResult("请输入病区");
            }
            if(StringUtils.isBlank(inpatNum) && StringUtils.isBlank(healthNum)){
                return ResultGenerator.genFailedResult("请输入住院号或者会员Id");
            }
            String newInpatNum=null;
            if(StringUtils.isNotBlank(inpatNum)){
                newInpatNum=inpatNum+"-1";
            }
            //取消出院
            patientInHospitalDTO = circulationLogMapper.queryFinishOutHospPatientInfoByInpatNum(wardId, newInpatNum, healthNum);
            if(patientInHospitalDTO==null){
                return ResultGenerator.genFailedResult("查无此人");
            }
            getPatientAge(patientInHospitalDTO);
        }else if(CirculationModelEnum.CANCLE_OUT_DEPT.getCode().equals(operationFlag)) {
            if(StringUtils.isBlank(wardId)){
                return ResultGenerator.genFailedResult("请输入病区");
            }
            if(StringUtils.isBlank(inpatNum) && StringUtils.isBlank(healthNum)){
                return ResultGenerator.genFailedResult("请输入住院号或者会员Id");
            }
            String newInpatNum=null;
            if(StringUtils.isNotBlank(inpatNum)){
                newInpatNum=inpatNum+"-1";
            }
            //取消转科转出
            patientInHospitalDTO = circulationLogMapper.queryFinishOutDeptPatientInfoByInpatNum(wardId, newInpatNum, healthNum);
            if(patientInHospitalDTO==null){
                return ResultGenerator.genFailedResult("查无此人");
            }
            getPatientAge(patientInHospitalDTO);
        }else if(CirculationModelEnum.CANCLE_IN_DEPT.getCode().equals(operationFlag)) {
            String babyFlag = null;
            List<Map<String, String>> pbstetricWardList = circulationLogMapper.queryObstetricWard(wardId, VarCodeEnum.OBSTETRICS_WARD.getVarCode());
            if (CollectionUtils.isNotEmpty(pbstetricWardList)) {
                babyFlag = "1";
            }
            //取消转科转入
            patientInHospitalDTO = circulationLogMapper.queryFinishInDeptPatientInfoByInpatNum2(wardId, bedNo, babyFlag);
            if(patientInHospitalDTO==null){
                return ResultGenerator.genFailedResult("查无此人");
            }
            Map<String, String> diagMap = this.getCurrentDiagName(patientInHospitalDTO.getInpatNum());
            if (diagMap != null) {
                patientInHospitalDTO.setDiagId(diagMap.get("diagId"));
                patientInHospitalDTO.setDiagName(diagMap.get("diagName"));
            }
            getPatientAge(patientInHospitalDTO);
        }
        return ResultGenerator.genOkResult(patientInHospitalDTO);
    }

    public Result queryBedNoByWardDeptId(String wardId,String id,Integer page,Integer pageSize,String keyWords){
        String babyFlag = null;
        List<Map<String, String>> pbstetricWardList = circulationLogMapper.queryObstetricWard(wardId,VarCodeEnum.OBSTETRICS_WARD.getVarCode());
        if(CollectionUtils.isNotEmpty(pbstetricWardList)){
            babyFlag="1";
        }
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = circulationLogMapper.queryBedNoByWardDeptId(wardId,id,null,babyFlag,null,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryDeptList(String id,Integer page,Integer pageSize,String keyWords){
        PageHelper.startPage(page, pageSize);
        List<Map<String, String>> list = patientInHospitalMapper.queryDeptList(id,keyWords);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryInDeptByInpatNum(String wardId,String inpatNum,String healthNum,String operationFlag){
        if(CirculationModelEnum.WAIT_IN_DEPT.getCode().equals(operationFlag)) {
            List<Map<String, String>> list = circulationLogMapper.queryWaitInDeptList(wardId, null, inpatNum, healthNum);
            if(CollectionUtils.isNotEmpty(list)){
                Result result = this.queryPatientInfo(list.get(0).get("circulationLogId"), list.get(0).get("inpatNum"), operationFlag);
                return result;
            }else{
                return ResultGenerator.genFailedResult("查无此人");
            }
        }
        return ResultGenerator.genOkResult();
    }

    public Result patientCheckLeaveHospital(String inpatNum,String operationFlag){
        //his接口
        List<Map<String, String>> checkResultList = new CopyOnWriteArrayList<>();
        List<Map<String, String>> resultList = new CopyOnWriteArrayList<>();
        List<Map<String, String>> resultList2 = new CopyOnWriteArrayList<>();
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");

        Map<String, Object> map = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("patient_id", inpatNum.split("-")[0]);
        param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));
        param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
        param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        requestMap.put("request", param);
        map.put("c_request", requestMap);
        if(CirculationModelEnum.WAIT_OUT_DEPT.getCode().equals(operationFlag)){
            map.put("operationID", ConstantEnum.HZQUERY_10027.getKey());
        }else{
            map.put("operationID", ConstantEnum.HZQUERY_10021.getKey());
        }
        log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", JSON.toJSONString(map));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            } else {
                if (jsonObject.getString("c_response") != null) {
                    Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                    });
                    Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");
                    if (response != null && response.get("result") != null) {
                        List<Map<String, String>> result = (List<Map<String, String>>) response.get("result");
                        if(CollectionUtils.isNotEmpty(result)){
                            checkResultList = result.stream().filter(x -> "1".equals(x.get("checkresult"))).collect(Collectors.toList());
                            if(CollectionUtils.isNotEmpty(checkResultList) && CirculationModelEnum.WAIT_OUT_DEPT.getCode().equals(operationFlag)) {
                                checkResultList.stream().forEach(x->{
                                    /*101 该病人有新开医嘱，不能出院！
                                    102 该病人还有没停的长期医嘱，停止吗?
                                    103 该病人产婴还有没停的长期医嘱，停止吗?
                                    104 该病人还有未停止的长期记账单，停止吗?
                                    105 该病人婴儿还有未停止的长期记账单，停止吗?
                                    106 该病人还有未确认或未发药的处方,不许转科
                                    107 该病人还有未确认或未发药的门诊处方,不许出院
                                    108 该病人还有未确认或未发药的门诊处方,是否继续转科？
                                    109 该病人还有未确认或未发药的处方,是否继续转科？
                                    110 该病人有未领药完成的医嘱，请处理后进行转科，是否继续转科？*/
                                    if("101".equals(x.get("checktype"))){
                                        x.put("checkmessage", "该病人有新开医嘱，不能转科！");
                                        x.put("sort", "1");
                                    }else if("107".equals(x.get("checktype"))){
                                        x.put("sort", "7");
                                    }else if("110".equals(x.get("checktype"))){
                                        x.put("sort", "10");
                                    }else{
                                        x.put("sort",x.get("checktype").substring(x.get("checktype").length()-1));
                                    }
                                    resultList.add(x);
                                });
                            }else if(CollectionUtils.isNotEmpty(checkResultList)) {
                                /*
                                    100 该病人还有未确认或未发药的处方,不许出院
                                    101 该病人有新开医嘱，不能出院！
                                    102 该病人还有没停的长期医嘱，停止吗?
                                    103 该病人产婴还有没停的长期医嘱，停止吗?
                                    104 该病人有未领药完毕医嘱
                                    105 该病人还有未发药毒麻处方，强行出院吗？
                                    106 有未记账的医嘱，不能出院。
                                */
                                checkResultList.stream().forEach(x->{
                                    if("100".equals(x.get("checktype")) ||  "101".equals(x.get("checktype")) || "102".equals(x.get("checktype")) ||  "103".equals(x.get("checktype")) ||  "104".equals(x.get("checktype")) ||  "106".equals(x.get("checktype")) ){
                                        x.put("sort",x.get("checktype").substring(x.get("checktype").length()-1));
                                    }else if("105".equals(x.get("checktype"))){
                                        x.put("sort","-1");
                                    }
                                    resultList.add(x);
                                });
                            }
                        }
                    }
                }
            }
        }
        //排序
        if (CollectionUtils.isNotEmpty(resultList)) {
            resultList2 = resultList.stream().sorted(Comparator.comparingInt(PatientCirculationServiceImpl::comparingBySort))
                        .collect(Collectors.toList());
        }
        return ResultGenerator.genOkResult(resultList2);
    }

    private static Integer comparingBySort(Map<String, String> map) {
        return Integer.parseInt(String.valueOf(map.get("sort")));
    }

    public String getYllbName(String yllb){
        String yllbName = "";
        if(StringUtils.isNotBlank(yllb)){
            if("11".equals(yllb)){
                yllbName="普通门诊";
            }else if("12".equals(yllb)){
                yllbName="定点药店购药";
            }else if("15".equals(yllb)){
                yllbName="市外转诊(异地)";
            }else if("16".equals(yllb)){
                yllbName="市外转诊(未经审批)";
            }else if("17".equals(yllb)){
                yllbName="市外转诊";
            }else if("18".equals(yllb)){
                yllbName="门诊特殊项目报销";
            }else if("21".equals(yllb)){
                yllbName="普通住院";
            }else if("22".equals(yllb)){
                yllbName="市外转院";
            }else if("23".equals(yllb)){
                yllbName="单病种";
            }else if("24".equals(yllb)){
                yllbName="市外转院(异地)";
            }else if("25".equals(yllb)){
                yllbName="市外转院(未经审批)";
            }else if("31".equals(yllb)){
                yllbName="特殊药品";
            }else if("32".equals(yllb)){
                yllbName="市外转诊(特药)";
            }else if("33".equals(yllb)){
                yllbName="市外转诊未经审批(特药)";
            }else if("34".equals(yllb)){
                yllbName="医疗补充结算";
            }else if("62".equals(yllb)){
                yllbName="工伤住院";
            }else if("63".equals(yllb)){
                yllbName="工伤康复";
            }else if("51".equals(yllb)){
                yllbName="生育门诊";
            }else if("52".equals(yllb)){
                yllbName="计划生育门诊";
            }else if("53".equals(yllb)){
                yllbName="生育住院";
            }else if("54".equals(yllb)){
                yllbName="计划生育住院";
            }else if("55".equals(yllb)){
                yllbName="生育并发症";
            }else if("71".equals(yllb)){
                yllbName="禽流感门诊";
            }else if("72".equals(yllb)){
                yllbName="禽流感住院";
            }
        }
        return yllbName;


    }

}
